<?php
namespace App\Models;

use App\Jobs\LingXingJob;
use App\Libs\wrapper\Task;
use App\Models\Common\Constant;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\Datawhole;
use App\Models\ResourceModel\GoodTransfersDetailModel;
class InventoryModel extends BaseModel
{
    // 出入库类型

    const TYPE_DETAIL = [
        '1' => '仓库调拨入库',
        '2' => '采购入库',
        '3' => '手工入库',
        '4' => '样品退回入库',
        '5' => '订单退货入库',
        '6' => 'fba出库',
        '7' => '仓库调拨出库',
        '8' => '第三方仓出库',
        '9' => '采购退货出库',
        '10' => '样品调拨出库',
        '11' => '手工出库',
        '12' => '订单出库',
        '13' => '工厂虚拟入库',
        '14' => '工厂虚拟出库',
        '15' => '验货申请',
        '16' => '调货申请',
        '17' =>'组货出库',
        '18' =>'组货入库'

    ];

    protected $goodTransfersDetailModel;
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->goodTransfersDetailModel = new GoodTransfersDetailModel();
    }

    public function getInventory($params){
        $posttype = $params['posttype']??1;
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $sku = isset($params['sku']) ? $params['sku'] : null;
        $user_id = isset($params['user_id']) ? $params['user_id'] : 0;
        $shop_id = isset($params['shop_id']) ? $params['shop_id'] : 0;
        //初始化查询
        $thisDb = Db::table('self_sku as a')
            ->leftJoin('self_spu as b','a.spu_id','=','b.id')
            ->leftJoin('self_custom_sku as c','a.custom_sku_id','=','c.id')
            ->leftJoin('self_color_size as d','c.size','=','d.name')
            ->leftJoin('shop as s','s.Id','=','a.shop_id');
        $thisDb2 = Db::table('self_sku as a')
            ->leftJoin('self_spu as b','a.spu','=','b.spu')
            ->leftJoin('self_custom_sku as c','a.custom_sku_id','=','c.id')
            ->leftJoin('shop as s','s.Id','=','a.shop_id');
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }
        if($params['select_type']=='sku'){
            if(!empty($sku)){
                $thisDb = $thisDb->where(function ($query) use ($sku){
                    $query->where('a.sku','like','%'.$sku.'%')->orWhere('a.old_sku','like','%'.$sku.'%');
                });
                $thisDb2 = $thisDb2->where(function ($query) use ($sku){
                    $query->where('a.sku','like','%'.$sku.'%')->orWhere('a.old_sku','like','%'.$sku.'%');
                });
            }
        }
        if($params['select_type']=='custom_sku'){
            if(!empty($sku)){
                $thisDb = $thisDb->where(function ($query) use ($sku){
                    $query->where('c.custom_sku','like','%'.$sku.'%')->orWhere('c.old_custom_sku','like','%'.$sku.'%');
                });
                $thisDb2 = $thisDb2->where(function ($query) use ($sku){
                    $query->where('c.custom_sku','like','%'.$sku.'%')->orWhere('c.old_custom_sku','like','%'.$sku.'%');
                });
            }
        }
        if($params['select_type']=='fnsku'){
            if(!empty($sku)){
                $product_detail = DB::table('product_detail')->where('fnsku','like','%'.$sku.'%')->select('sku_id')->first();
                if(!empty($product_detail)){
                    $thisDb = $thisDb->where('a.id',$product_detail->sku_id);
                }
            }
        }
        if($user_id!=0){
            $thisDb = $thisDb->where('a.user_id','=',$user_id);
            $thisDb2 = $thisDb2->where('a.user_id','=',$user_id);
        }
        if($shop_id!=0){
            $thisDb = $thisDb->where('a.shop_id','=',$shop_id);
            $thisDb2 = $thisDb2->where('a.shop_id','=',$shop_id);
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->whereIn('b.one_cate_id',$params['one_cate_id']);
            $thisDb2 = $thisDb2->whereIn('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['spu_id'])){
            $thisDb = $thisDb->whereIn('b.id',$params['spu_id']);
            $thisDb2 = $thisDb2->whereIn('b.id',$params['spu_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->whereIn('b.two_cate_id',$params['two_cate_id']);
            $thisDb2 = $thisDb2->whereIn('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->whereIn('b.three_cate_id',$params['three_cate_id']);
            $thisDb2 = $thisDb2->whereIn('b.three_cate_id',$params['three_cate_id']);
        }
        if(isset($params['custom_sku_name'])){
            $thisDb = $thisDb->where('c.name','like','%'.trim($params['custom_sku_name']).'%');
            $thisDb2 = $thisDb2->where('c.name','like','%'.trim($params['custom_sku_name']).'%');
        }
        $day_0_90_total = 0;
        $day_91_180_total = 0;
        $day_181_270_total = 0;
        $day_271_365_total = 0;
        $day_365_total = 0;
        if(isset($params['inventory_aged'])){
            $inventory_aged = Db::table('amazon_inventory_aged')
                ->where('snapshot_date',date('Y-m-d'));
            if($params['inventory_aged']==1){
                $inventory_aged = $inventory_aged->where('day_0_90','!=',0);
            }
            if($params['inventory_aged']==2){
                $inventory_aged = $inventory_aged->where('day_91_180','!=',0);
            }
            if($params['inventory_aged']==3){
                $inventory_aged = $inventory_aged->where('day_181_270','!=',0);
            }
            if($params['inventory_aged']==4){
                $inventory_aged = $inventory_aged->where('day_271_365','!=',0);
            }
            if($params['inventory_aged']==5){
                $inventory_aged = $inventory_aged->where('day_365','!=',0);
            }
            $inventory_aged= $inventory_aged
                ->select('sku_id','sku','day_0_90', 'day_91_180','day_181_270', 'day_271_365', 'day_365','your_price','sales_price')
                ->get()
                ->toArray();
            $inven_age = [];//库龄数组  sku=>五种库龄数值
            foreach ($inventory_aged as $age){
                $skuIds[] = $age->sku_id;
                $day_0_90_total += $age->day_0_90;
                $day_91_180_total += $age->day_91_180;
                $day_181_270_total += $age->day_181_270;
                $day_271_365_total += $age->day_271_365;
                $day_365_total += $age->day_365;
                $inven_age[$age->sku_id] = ['day_0_90'=>$age->day_0_90,'day_91_180'=>$age->day_91_180,'day_181_270'=>$age->day_181_270, 'day_271_365'=>$age->day_271_365,
                    'day_365'=>$age->day_365,'your_price'=>$age->your_price,'sales_price'=>$age->sales_price];
            }
            $skuIds = array_unique($skuIds);
            $thisDb = $thisDb->whereIn('a.id',$skuIds);
            $thisDb2 = $thisDb2->whereIn('a.id',$skuIds);
        }
        $totalData=$thisDb2->leftJoin('product_detail as d','a.id','=','d.sku_id')->select('a.id','d.in_stock_num','d.un_stock_num','d.in_bound_num','d.transfer_num')->get()->toArray();//数据总数
        $skuIds2 = array_column($totalData,'id');
        $count = count($totalData);

        if($posttype==1){
            $thisDb = $thisDb
                ->offset($page)
                ->limit($limit);
        }
        //执行查询
        $data = $thisDb
            ->where('s.platform_id',5)
            ->select('s.shop_name','a.sku','a.old_sku','c.img','a.user_id','a.shop_id','b.one_cate_id','b.two_cate_id','b.three_cate_id','c.size','d.sort','a.id','a.id')
            ->orderby('b.spu','ASC')
            ->orderby('c.color','ASC')
            ->orderby('d.sort','ASC')
            ->orderby('a.id','DESC')
            ->get()
            ->toArray();
        //新旧sku组合成数组
        if(!isset($skuIds)){
            $skuIds = array_column($data,'id');
            $inventory_aged = Db::table('amazon_inventory_aged')->where('snapshot_date',date('Y-m-d'));
            if(isset($params['one_cate_id'])||isset($params['two_cate_id'])||isset($params['three_cate_id'])||isset($params['sku'])
                ||isset($params['user_id'])||isset($params['shop_id'])){
                $inventory_aged = $inventory_aged->whereIn('sku_id',$skuIds2);
            }
            $inventory_aged = $inventory_aged->select('sku_id','sku','day_0_90', 'day_91_180','day_181_270', 'day_271_365','day_365','your_price','sales_price')->get()->toArray();
            $inven_age = [];//库龄数组  sku=>五种库龄数值
            foreach ($inventory_aged as $age){
                $day_0_90_total += $age->day_0_90;
                $day_91_180_total += $age->day_91_180;
                $day_181_270_total += $age->day_181_270;
                $day_271_365_total += $age->day_271_365;
                $day_365_total += $age->day_365;
                $inven_age[$age->sku_id] = ['day_0_90'=>$age->day_0_90,'day_91_180'=>$age->day_91_180,'day_181_270'=>$age->day_181_270, 'day_271_365'=>$age->day_271_365,
                    'day_365'=>$age->day_365,'your_price'=>$age->your_price,'sales_price'=>$age->sales_price];
            }
        }
        //查询库存
        $product_detail = Db::table('product_detail')->whereIn('sku_id',$skuIds)->select('sellersku','in_stock_num','un_stock_num','in_bound_num','transfer_num','sku_id')->get()->toArray();

        $inven = [];//库存数组  sku=>三种库存
        foreach ($product_detail as $detail){
            $inven[$detail->sku_id] = ['in_stock_num'=>$detail->in_stock_num,'in_bound_num'=>$detail->in_bound_num,'un_stock_num'=>$detail->un_stock_num,'transfer_num'=>$detail->transfer_num];
        }

        //库存合计
        $in_stock__total_num = 0;
        $in_bound_num = 0;
        $un_stock_num = 0;
        $transfer_num = 0;
        foreach ($totalData as $td){
            $in_stock__total_num += $td->in_stock_num;
            $in_bound_num += $td->in_bound_num;
            $un_stock_num += $td->un_stock_num;
            $transfer_num += $td->transfer_num;
        }
        //

        foreach ($data as $key =>$val){
            //运营
            $val->account = '';
            $account = $this->GetUsers($val->user_id);
            if($account){
                $val->account = $account['account'];
            }
            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);
            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }
            //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }
            //库存赋值
            if(array_key_exists($val->id,$inven)){
                $data[$key]->in_stock_num = $inven[$val->id]['in_stock_num'];
                $data[$key]->un_stock_num = $inven[$val->id]['un_stock_num'];
                $data[$key]->in_bound_num = $inven[$val->id]['in_bound_num'];
                $data[$key]->transfer_num = $inven[$val->id]['transfer_num'];
            }else{
                $data[$key]->in_stock_num = 0;
                $data[$key]->in_bound_num = 0;
                $data[$key]->transfer_num = 0;
            }
            //库龄赋值
            if(array_key_exists($val->id,$inven_age)){
                $data[$key]->day_0_90 = $inven_age[$val->id]['day_0_90'];
                $data[$key]->day_91_180 = $inven_age[$val->id]['day_91_180'];
                $data[$key]->day_181_270 = $inven_age[$val->id]['day_181_270'];
                $data[$key]->day_271_365 = $inven_age[$val->id]['day_271_365'];
                $data[$key]->day_365 = $inven_age[$val->id]['day_365'];
                $data[$key]->your_price = $inven_age[$val->id]['your_price'];
                $data[$key]->sales_price = $inven_age[$val->id]['sales_price'];
            }else{
                $data[$key]->day_0_90 = 0;
                $data[$key]->day_91_180 = 0;
                $data[$key]->day_181_270 = 0;
                $data[$key]->day_271_365 = 0;
                $data[$key]->day_365 = 0;
                $data[$key]->your_price = 0;
                $data[$key]->sales_price = 0;
            }

            if($val->old_sku!=null&&$val->old_sku!=''){
                $val->sku = $val->old_sku;
            }

        }

        $posttype = $params['posttype']??1;
        if($posttype==2){
            if(count($data)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']='海外仓库存导出表'.time();

            $list = [
                'shop_name'=>'店铺名',
                'sku'=>'渠道sku',
                'old_sku'=>'渠道sku(旧)',
                'account'=>'运营',
                'in_bound_num'=>'在途',
                'un_stock_num'=>'不可售',
                'in_stock_num'=>'可售',
                'transfer_num'=>'预留',
                'day_0_90'=>'库龄<90',
                'day_91_180'=>'库龄90-180',
                'day_181_270'=>'库龄180-270',
                'day_271_365'=>'库龄270-365',
                'day_365'=>'库龄>365',
            ];

            // var_dump($user_ids);
            $p['title_list']  = $list;
            $p['data'] =  $data;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '库存管理-海外仓导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

        return [
            'data' => $data,
            'totalNum' => $count,
            'in_stock_total_num'=>$in_stock__total_num,
            'un_stock_num'=>$un_stock_num,
            'in_bound_num'=>$in_bound_num,
            'transfer_num'=>$transfer_num,
            'total_inventory'=>$in_stock__total_num+$in_bound_num+$un_stock_num+$transfer_num,
            'day_0_90_total'=>$day_0_90_total,
            'day_91_180_total'=>$day_91_180_total,
            'day_181_270_total'=>$day_181_270_total,
            'day_271_365_total'=>$day_271_365_total,
            'day_365_total'=>$day_365_total
        ];
    }


    public function getInventoryTotal($params){
        //查询库存
        $product_detail = Db::table('product_detail')->select('in_stock_num','un_stock_num','in_bound_num','transfer_num')->get()->toArray();
        $inStockTotal = 0;
        $unStockTotal = 0;
        $inBoundTotal = 0;
        $transferTotal = 0;
        $cloudTotal = 0;
        $tonganTotal = 0;
        $quanzhouTotal = 0;
        $localTotal = 0;
        $depositTotal = 0;
        $factoryTotal = 0;
        $fbaTotal = 0;
        foreach ($product_detail as $v){
            $inStockTotal += $v->in_stock_num;
            $unStockTotal += $v->un_stock_num;
            $inBoundTotal += $v->in_bound_num;
            $transferTotal += $v->transfer_num;
        }
        $fbaTotal = $inStockTotal+$unStockTotal+$inBoundTotal+$transferTotal;

        $local_detail = Db::table('self_custom_sku')->select('cloud_num','tongan_inventory','quanzhou_inventory','deposit_inventory','factory_num')->get()->toArray();

        foreach ($local_detail as $d){
            $cloudTotal += $d->cloud_num;
            $tonganTotal += $d->tongan_inventory;
            $quanzhouTotal += $d->quanzhou_inventory;
            $depositTotal += $d->deposit_inventory;
            $factoryTotal += $d->factory_num;
        }

        $localTotal = $cloudTotal+$tonganTotal+$quanzhouTotal;


        return [
            'inStockTotal' => $inStockTotal,
            'unStockTotal' => $unStockTotal,
            'inBoundTotal' => $inBoundTotal,
            'transferTotal' => $transferTotal,
            'cloudTotal' => $cloudTotal,
            'tonganTotal' => $tonganTotal,
            'quanzhouTotal' => $quanzhouTotal,
            'depositTotal' => $depositTotal,
            'factoryTotal' => $factoryTotal,
            'fbaTotal' => $fbaTotal,
            'localTotal' => $localTotal
        ];
    }

    public function getSaiheInventory($params){
        $posttype = $params['posttype']??1;
        // $page = isset($params['page']) ? $params['page'] : 1;
        // $limit = isset($params['limit']) ? $params['limit'] : 30;
        $custom_sku = isset($params['custom_sku']) ? $params['custom_sku'] : null;
        $house_id = isset($params['house_id'])? $params['house_id'] : 1;
        //分页
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }


        //初始化查询
        $thisDb = Db::table('self_custom_sku as a')->leftjoin('self_spu as b','a.spu','=','b.spu')->leftJoin('self_color_size as c','a.size','=','c.name');

        if($custom_sku!=null){
            $custom_sku =trim($custom_sku);
            $thisDb = $thisDb->where('a.custom_sku','like','%'.$custom_sku.'%')->orWhere('a.old_custom_sku','like','%'.$custom_sku.'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->whereIn('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->whereIn('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->whereIn('b.three_cate_id',$params['three_cate_id']);
        }
        //数据总数
        $count=$thisDb->count();
        //执行查询
//        DB::connection()->enableQueryLog();
        if($posttype==1){
            $thisDb = $thisDb
                ->offset($page)
                ->limit($limit);
        }
        $data = $thisDb
            ->select('a.custom_sku','a.old_custom_sku','a.spu','b.one_cate_id','b.two_cate_id','b.three_cate_id','a.id','a.buy_price')
            ->orderby('a.spu','ASC')
            ->orderby('a.color','ASC')
            ->orderby('c.sort','ASC')
            ->orderby('a.id','DESC')
            ->get()
            ->toArray();
//        var_dump(DB::getQueryLog());
        //取出新旧库存sku组合成数组
        $custom_skuarr = array_column($data,'id');
//        $custom_skuarr = array_column($data,'custom_sku');
//        $old_custom_skuarr = array_column($data,'old_custom_sku');
//        $skuArr=array_merge($custom_skuarr,$old_custom_skuarr);
        //根据组合的库存sku数组查询赛盒同安fba仓，同安自发货仓，泉州仓库存
        if($house_id==1){
            $warehouse_id = [2,386];
        }else{
            $warehouse_id = [560];
        }
        $inventory = DB::table('saihe_inventory')->whereIn('custom_sku_id',$custom_skuarr)->whereIn('warehouse_id',$warehouse_id)->select('custom_sku','good_num','warehouse_id')->get()->toArray();
        // var_dump( $inventory );
        $fbaArr = [];
        $selfArr = [];
        $quanzhouArr = [];
        //三个仓的库存分别组成数组
        foreach ($inventory as $invenVal){
            if($house_id==1){
                if($invenVal->warehouse_id==2){
                    if(isset($fbaArr[$invenVal->custom_sku])){
                        $fbaArr[$invenVal->custom_sku] += $invenVal->good_num;
                    }else{
                        $fbaArr[$invenVal->custom_sku] = $invenVal->good_num;
                    }

                }
                if($invenVal->warehouse_id==386){
                    if(isset($selfArr[$invenVal->custom_sku])){
                        $selfArr[$invenVal->custom_sku] += $invenVal->good_num;
                    }else{
                        $selfArr[$invenVal->custom_sku] = $invenVal->good_num;
                    }

                }
            }else{
                if($invenVal->warehouse_id==560){
                    if(isset($quanzhouArr[$invenVal->custom_sku])){
                        $quanzhouArr[$invenVal->custom_sku] += $invenVal->good_num;
                    }else{
                        $quanzhouArr[$invenVal->custom_sku] = $invenVal->good_num;
                    }

                }
            }
        }

        // var_dump( $fbaArr);
        //查询库存sku的补货计划
        $buhuo_request = Db::table('amazon_buhuo_request as a')
            ->join('amazon_buhuo_detail as b','a.id','=','b.request_id')
            ->whereIn('b.custom_sku_id',$custom_skuarr)
            ->whereIn('a.request_status',[3,4,5,6,7])
            ->where('warehouse',$house_id)
            ->select('b.request_num','b.custom_sku', 'b.transportation_mode_name', 'b.transportation_type')
            ->get()->toArray();
        $courierArr = [];
        $shippingArr = [];
        $airArr = [];
        $kahangArr = [];
        $railwayArr = [];
        // 五种快递方式分别组成数组
        foreach ($buhuo_request as $requestVal){
            switch ($requestVal->transportation_type){
                case 1:
                    // 海运
                    if(isset($shippingArr[$requestVal->custom_sku])){
                        $shippingArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $shippingArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 2:
                    // 快递
                    if(isset($courierArr[$requestVal->custom_sku])){
                        $courierArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $courierArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 3:
                    // 空运
                    if(isset($airArr[$requestVal->custom_sku])){
                        $airArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $airArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 4:
                    // 铁路
                    if(isset($railwayArr[$requestVal->custom_sku])){
                        $railwayArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $railwayArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 5:
                    // 卡航
                    if(isset($kahangArr[$requestVal->custom_sku])){
                        $kahangArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $kahangArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                default:
                    break;
            }
        }
        //赋值
        foreach ($data as $key=>$val){
            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);
            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }
            //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }

            $data[$key]->inventory = 0;//库存

            $data[$key]->img = $this->GetCustomskuImg($val->custom_sku);//图片

            //库存赋值
            if($house_id==1){
                if(array_key_exists($val->old_custom_sku,$fbaArr)){
                    $fba_inventory = $fbaArr[$val->old_custom_sku];
                }elseif(array_key_exists($val->custom_sku,$fbaArr)){
                    $fba_inventory = $fbaArr[$val->custom_sku];
                }else{
                    $fba_inventory = 0;
                }
                if(array_key_exists($val->old_custom_sku,$selfArr)){
                    $self_inventory = $selfArr[$val->old_custom_sku];
                }elseif(array_key_exists($val->custom_sku,$selfArr)){
                    $self_inventory = $selfArr[$val->custom_sku];
                }else{
                    $self_inventory = 0;
                }
                $data[$key]->inventory = $fba_inventory+$self_inventory;
            }else{
                if(array_key_exists($val->old_custom_sku,$quanzhouArr)){
                    $data[$key]->inventory = $quanzhouArr[$val->old_custom_sku];
                }elseif(array_key_exists($val->custom_sku,$quanzhouArr)){
                    $data[$key]->inventory = $quanzhouArr[$val->custom_sku];
                }else{
                    $data[$key]->inventory = 0;
                }
            }


            //快递计划发货数量赋值
            if(array_key_exists($val->old_custom_sku,$courierArr)){
                $data[$key]->courier_num = $courierArr[$val->old_custom_sku];
            }elseif(array_key_exists($val->custom_sku,$courierArr)){
                $data[$key]->courier_num = $courierArr[$val->custom_sku];
            }else{
                $data[$key]->courier_num = 0;
            }
            //海运计划发货数量赋值
            if(array_key_exists($val->old_custom_sku,$shippingArr)){
                $data[$key]->shipping_num = $shippingArr[$val->old_custom_sku];
            }elseif(array_key_exists($val->custom_sku,$shippingArr)){
                $data[$key]->shipping_num = $shippingArr[$val->custom_sku];
            }else{
                $data[$key]->shipping_num = 0;
            }
            //空运计划发货数量赋值
            if(array_key_exists($val->old_custom_sku,$airArr)){
                $data[$key]->air_num = $airArr[$val->old_custom_sku];
            }elseif(array_key_exists($val->custom_sku,$airArr)){
                $data[$key]->air_num = $airArr[$val->custom_sku];
            }else{
                $data[$key]->air_num = 0;
            }
            // 铁路计划发货数量赋值
            if(array_key_exists($val->old_custom_sku,$railwayArr)){
                $data[$key]->railway_num = $railwayArr[$val->old_custom_sku];
            }elseif(array_key_exists($val->custom_sku,$railwayArr)){
                $data[$key]->railway_num = $railwayArr[$val->custom_sku];
            }else{
                $data[$key]->railway_num = 0;
            }
            // 卡航计划发货数量赋值
            if(array_key_exists($val->old_custom_sku,$kahangArr)){
                $data[$key]->kahang_num = $kahangArr[$val->old_custom_sku];
            }elseif(array_key_exists($val->custom_sku,$kahangArr)){
                $data[$key]->kahang_num = $kahangArr[$val->custom_sku];
            }else{
                $data[$key]->kahang_num = 0;
            }
            //计划发货数量合计
            $data[$key]->total_num = $data[$key]->courier_num+$data[$key]->shipping_num+$data[$key]->air_num+$data[$key]->railway_num+$data[$key]->kahang_num;
            $data[$key]->reduce_num = $data[$key]->inventory - $data[$key]->total_num;
            //库存周转天数
            $data[$key]->turnover =  $data[$key]->total_num>0 ? round( $data[$key]->inventory/$data[$key]->total_num,2) : 0;

            if($val->old_custom_sku!=null||$val->old_custom_sku!=''){
                $val->custom_sku = $val->old_custom_sku;
            }
        }



        if($posttype==2){
            if(count($data)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            if($house_id==1){
                $house = '同安';
            }else{
                $house = '泉州';
            }

            $p['title']=$house.'仓库存导出表'.time();

            $list = [
                'custom_sku'=>'库存sku',
                'old_custom_sku'=>'库存sku(旧)',
//                'img'=>'图片',
                'buy_price'=>'参考成本价',
                'one_cate'=>'大类',
                'three_cate'=>'三类',
                'inventory'=>$house.'仓库存',
                'shipping_num'=>'计划出货-海运',
                'air_num'=>'计划出货-空运',
                'courier_num'=>'计划出货-快递',
                'railway_num' => '计划出货-铁路',
                'kahang_num' => '计划出货-卡航',
                'total_num'=>'计划出货-合计',
                'turnover'=>'库存周转天数',
            ];

            // var_dump($user_ids);
            $p['title_list']  = $list;
            $p['data'] =  $data;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '库存管理-'.$house.'仓导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }


        return [
            'data' => $data,
            'totalNum' => $count,
        ];
    }

    //同安仓-泉州仓出入库记录
    public function houseData($params){
        $custom_sku = isset($params['custom_sku'])? $params['custom_sku'] : null;
        $start_time = isset($params['start_time'])? $params['start_time'] : date('Y-01-01 00:00:00');;
        $end_time = isset($params['end_time'])? $params['end_time'] : date('Y-m-d H:i:s');
        $house_id = isset($params['house_id'])? $params['house_id'] : 1;
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }
        if(empty($custom_sku)){
            return [
                'data' => '',
                'totalNum' => '',
            ];
        }
        //初始化查询
        $data = DB::table('saihe_warehouse_log')->where('custom_sku',$custom_sku);

        if(!empty($start_time)&&!empty($end_time)){
            $data = $data->whereBetween('operation_date', [$start_time, $end_time]);
        }
        //$house_id=>array();
        //2=>同安fba仓  386=>同安自发货仓  560=>泉州仓

        if($house_id==1){
            $data = $data->whereIn('warehouse_id',[2,386]);
        }else{
            $data = $data->whereIn('warehouse_id',[560]);
        }

        $count = $data->count();
        //执行查询
        $data = $data->offset($pagenNum)->limit($limit)->select('custom_sku','operation_num','operation_date','warehouse_name','operation_username','remark','type')->get()->toArray();
        return [
            'data' => $data,
            'totalNum' => $count,
        ];
    }

    //云仓出入库记录
    public function cloudData($params){
        $custom_sku = isset($params['custom_sku'])? $params['custom_sku'] : null;
        $start_time = isset($params['start_time'])? $params['start_time'] : date('Y-01-01 00:00:00');
        $end_time = isset($params['end_time'])? $params['end_time'] : date('Y-m-d H:i:s');
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }
        if(empty($custom_sku)){
            return [
                'data' => '',
                'totalNum' => '',
            ];
        }
        //初始化查询
        $data = DB::table('cloudhouse_record')->where('custom_sku',$custom_sku);

        if(!empty($start_time)&&!empty($end_time)){
            $data = $data->whereBetween('createtime', [$start_time, $end_time]);
        }

        $count = $data->count();
        //执行查询
        $data = $data->offset($pagenNum)->limit($limit)->select('*')->get()->toArray();
        return [
            'data' => $data,
            'totalNum' => $count,
        ];
    }

    //库存总表
    public function getAllInventory($params){
        $posttype = $params['posttype']??1;

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $custom_sku = isset($params['custom_sku']) ? $params['custom_sku'] : null;

        $spuIds = isset($params['spu_id']) ? $params['spu_id'] : null;

        $colorIds = isset($params['color_id']) ? $params['color_id'] : null;

        //初始化查询
        $thisDb = Db::table('self_custom_sku as a')
            ->leftjoin('self_spu as b','a.spu_id','=','b.id')
            ->leftJoin('self_color_size as c','a.size','=','c.name');

        if($custom_sku!=null){
            $custom_sku =trim($custom_sku);
            $thisDb = $thisDb->where('a.custom_sku','like','%'.$custom_sku.'%')->orWhere('a.old_custom_sku','like','%'.$custom_sku.'%');
        }
        if(isset($params['custom_sku_name'])){
            $thisDb = $thisDb->where('a.name','like','%'.trim($params['custom_sku_name']).'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->whereIn('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->whereIn('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->whereIn('b.three_cate_id',$params['three_cate_id']);
        }
        if($spuIds!=null){
            $thisDb = $thisDb->whereIn('b.id',$spuIds);
        }
        if($colorIds!=null){
            $thisDb = $thisDb->whereIn('a.color_id',$colorIds);
        }
        //数据总数
        $total=$thisDb->select('a.tongan_inventory','a.id')
            ->get();
        $total = json_decode(json_encode($total),true);
        $custom_skuarr2 = array_column($total,'id');
        $count = 0;

        $inventory_total = 0;
        foreach ($total as $tt){
            $inventory_total += $tt['tongan_inventory'];
            $count++;
        }

        if($posttype==1){
            $thisDb = $thisDb
                ->offset($page)
                ->limit($limit);
        }

        $data = $thisDb
            ->select('a.name','a.custom_sku','a.old_custom_sku','a.spu','b.old_spu','b.one_cate_id','b.two_cate_id','b.three_cate_id','c.id as color_id',
                'a.id','a.tongan_inventory','a.buy_price')
            ->orderby('a.spu','ASC')
            ->orderby('a.color','ASC')
            ->orderby('c.sort','ASC')
            ->get()
            ->toArray();

        $custom_skuarr = array_column($data,'id');

        //查询已开合同数据
        $buhuo_request = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->whereIn('a.custom_sku_id',$custom_skuarr)
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0)
            ->select('a.custom_sku_id','a.num','a.contract_no')
            ->get()->toArray();

        $buhuo_request2 = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no');
        if(!empty($params['custom_sku'])||!empty($params['one_cate_id'])||!empty($params['two_cate_id'])
            ||!empty($params['three_cate_id'])||!empty($params['spu_id'])||!empty($params['color_id'])){
            $buhuo_request2 = $buhuo_request2->whereIn('a.custom_sku_id',$custom_skuarr2);
        }

        $buhuo_request2 = $buhuo_request2
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0)
            ->select('a.custom_sku_id','a.num','a.contract_no')
            ->get()->toArray();

        $contractNum = [];
        $contractArr = [];
        foreach ($buhuo_request as $b){
            if(isset($contractNum[$b->custom_sku_id])){
                $contractNum[$b->custom_sku_id] += $b->num;
            }else{
                $contractNum[$b->custom_sku_id] = $b->num;
            }
            $contractArr[] = $b->contract_no;
        }
        $contractArr = array_unique($contractArr);
        $contractNum2 = [];
        $contractArr2 = [];
        $factory_total = 0;
        foreach ($buhuo_request2 as $bb){
            if(isset($contractNum2[$bb->custom_sku_id])){
                $contractNum2[$bb->custom_sku_id] += $bb->num;
            }else{
                $contractNum2[$bb->custom_sku_id] = $bb->num;
            }
            $factory_total += $bb->num;

            $contractArr2[] = $bb->contract_no;
        }
        $contractArr2 = array_unique($contractArr2);
        //查询合同已出数据
        $goods_transfers = Db::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->whereIn('b.contract_no',$contractArr)
            ->whereIn('b.custom_sku_id',$custom_skuarr)
            ->where('a.is_push','>',0)
            ->where('a.type',1)
            ->select('a.type_detail','b.receive_num','b.custom_sku_id')
            ->get()->toArray();

        foreach ($goods_transfers as $g){
            if(isset($contractNum[$g->custom_sku_id])){
                if($g->type_detail==2){
                    $contractNum[$g->custom_sku_id] -= $g->receive_num;
                }
                if($g->type_detail==9){
                    $contractNum[$g->custom_sku_id] += $g->receive_num;
                }
            }
        }

        $goods_transfers2 = Db::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->whereIn('b.contract_no',$contractArr2);
        if(!empty($params['custom_sku'])||!empty($params['one_cate_id'])||!empty($params['two_cate_id'])
            ||!empty($params['three_cate_id'])||!empty($params['spu_id'])||!empty($params['color_id'])){
            $goods_transfers2 = $goods_transfers2->whereIn('b.custom_sku_id',$custom_skuarr2);
        }
        $goods_transfers2 = $goods_transfers2
            ->where('a.is_push','>',0)
            ->where('a.type',1)
            ->select('a.type_detail','b.receive_num','b.custom_sku_id')
            ->get()->toArray();



        foreach ($goods_transfers2 as $gg){
            if(isset($contractNum2[$gg->custom_sku_id])){
                if($gg->type_detail==2){
                    $contractNum2[$gg->custom_sku_id] -= $gg->receive_num;
                    $factory_total -= $gg->receive_num;
                }
                if($gg->type_detail==9){
                    $contractNum2[$gg->custom_sku_id] += $gg->receive_num;
                    $factory_total += $gg->receive_num;
                }
            }
        }

        // 查询待入库库存情况
        $request = DB::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
//            ->where(function($query) use($warehouse_id){
//                $query->where('a.out_house',$warehouse_id)->orWhere('a.in_house',$warehouse_id);
//            })
            ->whereIn('a.is_push',[1,2,4])
            ->whereIn('a.type_detail',$this->GetFieldTypeDetail3())
            ->select('b.transfers_num', 'b.custom_sku_id','a.order_no', 'a.type_detail','b.receive_num')
            ->get()
            ->toArray();
        $shelfArr = [];
        $shelf_total = 0;
        if(!empty($request)){
            foreach ($request as $bd){
                $shelf_total += $bd->transfers_num - $bd->receive_num;
                if(isset($shelfArr[$bd->custom_sku_id])){
                    $shelfArr[$bd->custom_sku_id] += $bd->transfers_num - $bd->receive_num;
                }else{
                    $shelfArr[$bd->custom_sku_id] = $bd->transfers_num - $bd->receive_num;
                }
            }
        }


        //赋值
        foreach ($data as $key=>$val){
            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);

            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }
            //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }

            $data[$key]->img = $this->GetCustomskuImg($val->custom_sku);//图片

            if(isset($contractNum[$val->id])){
                $data[$key]->factory_num = $contractNum[$val->id]>0?$contractNum[$val->id]:0;
            }else{
                $data[$key]->factory_num = 0;
            }
            

            if(isset($shelfArr[$val->id])){
                $data[$key]->shelf_num = $shelfArr[$val->id];
            }else{
                $data[$key]->shelf_num = 0;
            }



        }
        if($posttype==2){

            $p['title']='库存总表'.time();


            $list = [
                'spu'=> '款号',
                'old_spu'=> '旧款号',
                'custom_sku'=>'库存sku',
                'old_custom_sku'=>'库存sku(旧)',
                'name'=>'商品名称',
                'one_cate'=>'大类',
                'two_cate'=>'大类',
                'three_cate'=>'三类',
                'tongan_inventory'=>'仓库库存',
                'shelf_num'=>'在途待入库',
                'factory_inventory'=>'生产中库存'
            ];

            $p['title_list']  = $list;
            $p['data'] =  $data;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '库存管理导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return [
            'data' => $data,
            'total_inventory'=>$inventory_total,
            'total_factory'=>$factory_total,
            'total'=>$inventory_total+$factory_total+$shelf_total,
            'totalNum' => $count,
            'shelf_total' => $shelf_total,
        ];

    }

    //本地库存接口
    public function getCloudInventory($params){

        $posttype = $params['posttype']??1;

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $custom_sku = isset($params['custom_sku']) ? $params['custom_sku'] : null;

        $warehouse_id = isset($params['warehouse_id']) ? $params['warehouse_id'] : 1;

        $spuIds = isset($params['spu_id']) ? $params['spu_id'] : null;

        $colorIds = isset($params['color_id']) ? $params['color_id'] : null;

        //初始化查询
        $thisDb = Db::table('self_custom_sku as a')
            ->leftjoin('self_spu as b','a.spu_id','=','b.id')
            ->leftJoin('self_color_size as c','a.size','=','c.name');

        if($custom_sku!=null){
            $custom_sku =trim($custom_sku);
            $thisDb = $thisDb->where('a.custom_sku','like','%'.$custom_sku.'%')->orWhere('a.old_custom_sku','like','%'.$custom_sku.'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->whereIn('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->whereIn('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->whereIn('b.three_cate_id',$params['three_cate_id']);
        }
        if($spuIds!=null){
            $thisDb = $thisDb->whereIn('b.id',$spuIds);
        }
        if($colorIds!=null){
            $thisDb = $thisDb->whereIn('a.color_id',$colorIds);
        }
        if(empty($custom_sku)){
            $thisDb = $thisDb->where(self::WAREHOUSE[$warehouse_id],'>',0);
        }
        if(isset($params['custom_sku_name'])){
            $thisDb = $thisDb->where('a.name','like','%'.trim($params['custom_sku_name']).'%');
        }
        //数据总数
        $total=$thisDb->select('a.tongan_inventory','a.quanzhou_inventory','a.cloud_num','a.deposit_inventory','a.direct_inventory','a.shenzhen_inventory')
            ->get();
        $total = json_decode(json_encode($total),true);
        $count = 0;
        $inventory_total = 0;
        foreach ($total as $tt){
            $inventory_total += $tt[self::WAREHOUSE[$warehouse_id]];
            $count++;
        }

        //执行查询
//            DB::connection()->enableQueryLog();
        if($posttype==1){
            $thisDb = $thisDb
                ->offset($page)
                ->limit($limit);
        }

        $data = $thisDb
            ->select('a.name','a.custom_sku','a.old_custom_sku','b.spu','b.old_spu','b.one_cate_id','b.two_cate_id','b.three_cate_id','c.id as color_id',
                'a.cloud_num','a.id','a.factory_num','a.tongan_inventory','a.quanzhou_inventory','a.deposit_inventory','a.direct_inventory','a.shenzhen_inventory','a.buy_price')
            ->orderby('a.spu','ASC')
            ->orderby('a.color','ASC')
            ->orderby('c.sort','ASC')
            ->get()
            ->toArray();

        $idArr = array_column($data,'id');
        // 查询库存情况
        $lockNum = $this->inventoryDetail($idArr,$warehouse_id,$data);

        $outArr = [];
        $cloudhouse_record = DB::table('cloudhouse_record')
            ->whereIn('custom_sku_id',$idArr)
            ->whereIn('type_detail',[6,8,12])
            ->where('createtime','>','2023-06-18 00:00:00')
            ->select('custom_sku_id','num')->get()->toArray();
        if(!empty($cloudhouse_record)){
            foreach ($cloudhouse_record as $r){
                if(isset($outArr[$r->custom_sku_id])){
                    $outArr[$r->custom_sku_id] += $r->num;
                }else{
                    $outArr[$r->custom_sku_id] = $r->num;
                }
            }
        }

        //赋值
        foreach ($data as $key=>$val){
            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);
            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }
                //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }

            $data[$key]->lockRes = $lockNum[$val->id];

            if($lockNum){
                if(isset($lockNum[$val->id])){
                    $data[$key]->inventory = $lockNum[$val->id]['inventory'];
                    $data[$key]->intsock_num = $lockNum[$val->id]['intstock_num'];
                    $data[$key]->lock_num = $lockNum[$val->id]['lock_num'];
                    $data[$key]->shelf_num = $lockNum[$val->id]['shelf_num'];
                    $data[$key]->delist_num = $lockNum[$val->id]['delist_num'];
                    $data[$key]->occupy_num = $lockNum[$val->id]['occupy_num'];
                    $data[$key]->bad_num = $lockNum[$val->id]['bad_num'];
                }else{
                    $data[$key]->inventory = 0;
                    $data[$key]->intsock_num = 0;
                    $data[$key]->lock_num = 0;
                    $data[$key]->shelf_num = 0;
                    $data[$key]->delist_num = 0;
                    $data[$key]->occupy_num = 0;
                    $data[$key]->bad_num = 0;
                }
            }

            if(isset($outArr[$val->id])){
                $data[$key]->outNum = $outArr[$val->id];
            }else{
                $data[$key]->outNum = 0;
            }
            $data[$key]->moveRatio = $lockNum[$val->id]['inventory']>0?round($data[$key]->outNum/$lockNum[$val->id]['inventory'],2):$data[$key]->outNum/1;
            $data[$key]->moveRatio = ($data[$key]->moveRatio*100).'%';
            $data[$key]->img = $this->GetCustomskuImg($val->custom_sku);//图片


        }


        if($posttype==2){

            $warehouse = DB::table('cloudhouse_warehouse')->where('id',$params['warehouse_id'])->select('warehouse_name')->first();
            if(!empty($warehouse)){
                $warehouse_title = $warehouse->warehouse_name;
            }else{
                $warehouse_title = '';
            }
            $p['title']=$warehouse_title.'库存导出表'.time();
            

            $list = [
                    'custom_sku'=>'库存sku',
                    'old_custom_sku'=>'库存sku(旧)',
//                    'img'=>'图片',
                    'spu' => 'spu',
                    'old_spu' => '旧spu',
                    'one_cate'=>'大类',
                    'two_cate'=>'大类',
                    'three_cate'=>'三类',
                    'inventory'=>'当前库存',
                    'intsock_num'=>'可用库存',
                    'occupy_num'=>'已占用库存',
                    'lock_num'=>'锁定库存',
                    'delist_num' => '已拣货库存',
                    'shelf_num' => '待入库库存',
                    'outNum' => '平台已出库数量',
                    'moveRatio' =>'动销率',
            ];

            $p['title_list']  = $list;
            $p['data'] =  $data;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '库存管理-'.$warehouse_title.'导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return [
            'data' => $data,
            'total_inventory'=>$inventory_total,
            'totalNum' => $count,
        ];
    }

    public function factoryInventory($params){

        $posttype = $params['posttype']??1;

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $custom_sku = isset($params['custom_sku']) ? $params['custom_sku'] : null;

        $spuIds = isset($params['spu_id']) ? $params['spu_id'] : null;

        $colorIds = isset($params['color_id']) ? $params['color_id'] : null;

        //分页

        //初始化查询
        $thisDb = Db::table('self_custom_sku as a')
            ->leftjoin('self_spu as b','a.spu_id','=','b.id')
            ->leftJoin('self_color_size as c','a.size','=','c.name');
        $thisDb2 = $thisDb;
        if($custom_sku!=null){
            $custom_sku =trim($custom_sku);
            $thisDb = $thisDb->where('a.custom_sku','like','%'.$custom_sku.'%')->orWhere('a.old_custom_sku','like','%'.$custom_sku.'%');
            $thisDb2 = $thisDb2->where('a.custom_sku','like','%'.$custom_sku.'%')->orWhere('a.old_custom_sku','like','%'.$custom_sku.'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->whereIn('b.one_cate_id',$params['one_cate_id']);
            $thisDb2 = $thisDb2->whereIn('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->whereIn('b.two_cate_id',$params['two_cate_id']);
            $thisDb2 = $thisDb2->whereIn('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->whereIn('b.three_cate_id',$params['three_cate_id']);
            $thisDb2 = $thisDb2->whereIn('b.three_cate_id',$params['three_cate_id']);
        }

        if($spuIds!=null){
            $thisDb = $thisDb->whereIn('b.id',$spuIds);
            $thisDb2 = $thisDb2->whereIn('b.id',$spuIds);
        }
        if($colorIds!=null){
            $thisDb = $thisDb->whereIn('a.color_id',$colorIds);
            $thisDb2 = $thisDb2->whereIn('a.color_id',$colorIds);
        }
        if(isset($params['custom_sku_name'])){
            $thisDb = $thisDb->where('a.name','like','%'.trim($params['custom_sku_name']).'%');
            $thisDb2 = $thisDb2->where('a.name','like','%'.trim($params['custom_sku_name']).'%');
        }
        //数据总数
        $total = $thisDb2->select('a.id')->get()->toArray();
        $count = count($total);
        $custom_skuarr2 = array_column($total,'id');

        if($posttype==1){
            $thisDb = $thisDb
                ->offset($page)
                ->limit($limit);
        }
        $data = $thisDb
            ->select('a.custom_sku','a.old_custom_sku','a.spu','b.one_cate_id','b.two_cate_id','b.three_cate_id','c.id as color_id','a.id','a.id as custom_sku_id')
            ->orderby('a.spu','ASC')
            ->orderby('a.color','ASC')
            ->orderby('c.sort','ASC')
            ->get()
            ->toArray();

        //取出新旧库存sku组合成数组
        $custom_skuarr = array_column($data,'id');
//        $old_custom_skuarr = array_column($data,'old_custom_sku');
//        $skuArr=array_merge($custom_skuarr,$old_custom_skuarr);
        //查询已开合同数据
        $buhuo_request = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->whereIn('a.custom_sku_id',$custom_skuarr)
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0)
            ->select('a.custom_sku_id','a.num','a.contract_no')
            ->get()->toArray();

        $buhuo_request2 = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no');
        if(!empty($params['custom_sku'])||!empty($params['one_cate_id'])||!empty($params['two_cate_id'])
            ||!empty($params['three_cate_id'])||!empty($params['spu_id'])||!empty($params['color_id'])){
            $buhuo_request2 = $buhuo_request2->whereIn('a.custom_sku_id',$custom_skuarr2);
        }
        $buhuo_request2 = $buhuo_request2
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0)
            ->select('a.custom_sku_id','a.num','a.contract_no')
            ->get()->toArray();

        $contractNum = [];
        $contractArr = [];
        foreach ($buhuo_request as $b){
            if(isset($contractNum[$b->custom_sku_id])){
                $contractNum[$b->custom_sku_id] += $b->num;
            }else{
                $contractNum[$b->custom_sku_id] = $b->num;
            }

            $contractArr[] = $b->contract_no;

        }
        $contractArr = array_unique($contractArr);

        $contractNum2 = [];
        $contractArr2 = [];
        $total_inventory = 0;
        foreach ($buhuo_request2 as $bb){
            if(isset($contractNum2[$bb->custom_sku_id])){
                $contractNum2[$bb->custom_sku_id] += $bb->num;
            }else{
                $contractNum2[$bb->custom_sku_id] = $bb->num;
            }
            $total_inventory += $bb->num;

            $contractArr2[] = $bb->contract_no;
        }

        $contractArr2 = array_unique($contractArr2);
        //查询合同已出数据
        $goods_transfers = Db::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->whereIn('b.contract_no',$contractArr)
            ->whereIn('b.custom_sku_id',$custom_skuarr)
            ->where('a.is_push','>',0)
            ->where('a.type',1)
            ->select('a.type_detail','b.receive_num','b.custom_sku_id')
            ->get()->toArray();

        foreach ($goods_transfers as $g){
            if(isset($contractNum[$g->custom_sku_id])){
                if($g->type_detail==2){
                    $contractNum[$g->custom_sku_id] -= $g->receive_num;
                }
                if($g->type_detail==9){
                    $contractNum[$g->custom_sku_id] += $g->receive_num;
                }
            }
        }

        $goods_transfers2 = Db::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->whereIn('b.contract_no',$contractArr2);
        if(!empty($params['custom_sku'])||!empty($params['one_cate_id'])||!empty($params['two_cate_id'])
            ||!empty($params['three_cate_id'])||!empty($params['spu_id'])||!empty($params['color_id'])){
            $goods_transfers2 = $goods_transfers2->whereIn('b.custom_sku_id',$custom_skuarr2);
        }
        $goods_transfers2 = $goods_transfers2
            ->where('a.is_push','>',0)
            ->where('a.type',1)
            ->select('a.type_detail','b.receive_num','b.custom_sku_id')
            ->get()->toArray();



        foreach ($goods_transfers2 as $gg){
            if(isset($contractNum2[$gg->custom_sku_id])){
                if($gg->type_detail==2){
                    $contractNum2[$gg->custom_sku_id] -= $gg->receive_num;
                    $total_inventory -= $gg->receive_num;
                }
                if($gg->type_detail==9){
                    $contractNum2[$gg->custom_sku_id] += $gg->receive_num;
                    $total_inventory += $gg->receive_num;
                }
            }
        }




        //赋值
        foreach ($data as $key=>$val){
            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);
            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }


            //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }
            if(isset($contractNum[$val->custom_sku_id])){
                $data[$key]->factory_inventory = $contractNum[$val->custom_sku_id]>0? $contractNum[$val->custom_sku_id]:0;
            }else{
                $data[$key]->factory_inventory = 0;
            }

            $data[$key]->img = $this->GetCustomskuImg($val->custom_sku);//图片
            if($val->old_custom_sku!=null||$val->old_custom_sku!=''){
                $val->custom_sku = $val->old_custom_sku;
            }
        }

        if($posttype==2){
            if(count($data)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']='工厂库存导出表'.time();

            $list = [
                'custom_sku'=>'库存sku',
                'old_custom_sku'=>'库存sku(旧)',
//                'img'=>'图片',
                'one_cate'=>'大类',
                'three_cate'=>'三类',
                'factory_inventory'=>'工厂库存'
            ];

            // var_dump($user_ids);
            $p['title_list']  = $list;
            $p['data'] =  $data;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '库存管理-工厂虚拟仓导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return [
            'data' => $data,
            'totalNum' => $count,
            'total_inventory' => $total_inventory
        ];
    }

    //工厂虚拟仓库存-sku合同明细
    public function factorySku($params){

        $custom_sku = isset($params['custom_sku_id'])?$params['custom_sku_id']:'';

        $buhuo_request = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->where('a.custom_sku_id',$custom_sku)
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0)
            ->select('a.custom_sku_id','a.num','a.contract_no')
            ->get()->toArray();

        $contractNum = [];
        $contractArr = [];
        foreach ($buhuo_request as $b){
            if(isset($contractNum[$b->contract_no])){
                $contractNum[$b->contract_no] += $b->num;
            }else{
                $contractNum[$b->contract_no] = $b->num;
            }

            if(!in_array($b->contract_no,$contractArr)){
                $contractArr[] = $b->contract_no;
            }
        }

        //查询合同已出数据
        $goods_transfers = Db::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->whereIn('b.contract_no',$contractArr)
            ->where('b.custom_sku_id',$custom_sku)
            ->where('a.is_push','>',0)
            ->where('a.type',1)
            ->select('a.type_detail','b.receive_num','b.contract_no')
            ->get()->toArray();

        foreach ($goods_transfers as $g){
            if(isset($contractNum[$g->contract_no])){
                if($g->type_detail==2){
                    $contractNum[$g->contract_no] -= $g->receive_num;
                }
                if($g->type_detail==9){
                    $contractNum[$g->contract_no] += $g->receive_num;
                }
            }
        }

        return [
            'data' => $contractNum
        ];

    }

    public function goods_transfers($params){

//        return ['code'=>500,'type'=>'fail','data'=>'系统紧急维护中，暂时无法发货，预计在上午10点左右恢复'];

        if(empty($params['skuData'])){
            return ['code'=>500,'msg'=>'请选择要调动的商品'];
        }

        if(!empty($params['in_house'])){
            $in_house = $params['in_house'];
        }else{
            $in_house = 5;
        }

        if(!empty($params['out_house'])){
            $out_house = $params['out_house'];
        }else{
            // return ['code'=>500,'msg'=>'请选择仓库'];
            $out_house = 5;
        }

//        if ($params['type_detail'] == 15){
//            return ['code'=>500,'msg'=>'验货申请功能暂时关闭！有问题请咨询it人员！'];
//        }

        if (isset($params['token'])) {
            $token = $params['token'];
            $user_data = DB::table('users')->where('token', '=', $token)->select('Id', 'account')->get();
            $user_id = $user_data[0]->Id;
        }elseif (isset($params['user_id'])) {
            $user_id = $params['user_id'];
        }


        $createtime = date('Y-m-d H:i:s');

        if(is_array($params['skuData'])){
            $transfers['order_no'] = rand(100,999).time();
            $transfers['total_num'] = 0;
            $transfers['sku_count'] = count($params['skuData']);
            $transfers['out_house'] = $out_house;
            $transfers['in_house'] = $in_house;
            $transfers['type'] = $params['type'];
            $transfers['yj_arrive_time'] = $params['yj_arrive_time']??$createtime;
            $transfers['type_detail'] = $params['type_detail'];
            $transfers['address'] = isset($params['address'])? $params['address'] : '';
            $transfers['user_id'] = $user_id;
            $transfers['shop_id'] = isset($params['shop_id'])? $params['shop_id'] : 0;
            $transfers['text'] = isset($params['remark']) ? $params['remark'] : '';
            $transfers['third_party_no'] = isset($params['third_party_no']) ? $params['third_party_no'] : '';
            $transfers['createtime'] = $createtime;
            $transfers['update_cause'] = isset($params['update_cause'])?$params['update_cause']:0;
            $transfers['img_url'] = json_encode($params['img_url'] ?? []);
            $transfers['file_url'] = json_encode($params['file_url'] ?? []);
            $transfers['platform_id'] = isset($params['platform_id'])? $params['platform_id'] : 0;
            $transfers['receive_platform_id'] = isset($params['receive_platform_id']) ? $params['receive_platform_id'] : 0;
            $transfers['anomaly_order'] = isset($params['anomaly_order'])?$params['anomaly_order']:'';

            if($transfers['platform_id']!=0&&$transfers['receive_platform_id']!=0){
                if($transfers['platform_id']==$transfers['receive_platform_id']){
                    return ['code'=>500,'msg'=>'不能选择两个相同的平台'];
                }
            }

            if($transfers['shop_id']!=0){
                $shop_data = $this->GetShop($transfers['shop_id']);
                if($shop_data){
                    $transfers['platform_id'] = $shop_data['platform_id'];
                }
            }
            if($transfers['type_detail']!=11){
                if($transfers['platform_id']==0){
                    return ['code'=>500,'msg'=>'未获取到平台信息，无法操作'];
                }
            }

            $total_num = 0;
            //生成调拨数据
            db::beginTransaction();    //开启事务
            $transfers_id = DB::table('goods_transfers')->insertGetId($transfers);
            // var_dump($transfers_id );
            $customskus = array();

            if($transfers_id){
                if($params['type_detail']==9){
                    $box_id = $this->Addbox($transfers['order_no'],$out_house);
                    if(!$box_id){
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'生成中转箱任务失败'];
                    }
                }

                //同步库存到翎星
                if ($transfers['platform_id'] == 5) {
                    $lxParams      = [
                        'wid'          => 0,
                        'type'         => 0,
                        'product_list' => [],
                    ];
                }


                //组合库存sku  先判断是否有成员数据相同
                if($params['type_detail']==17){
                    $rt_msg = [];
                    $cus_is_in = [];
                    $if_err = false;
                    foreach ($params['skuData'] as $val){
                        $cus_is_in_id = $val['group_custom_sku_id'];
                        $cus_is_in[$cus_is_in_id]['cus'][] = $val['custom_sku'];
                        if(isset($cus_is_in[$cus_is_in_id]['num'])){
                            $cus_is_in[$cus_is_in_id]['num'] +=$val['num'];
                        }else{
                            $cus_is_in[$cus_is_in_id]['num'] =$val['num'];
                        }



                        if($cus_is_in[$cus_is_in_id]['num']>$val['intsock_num']){
                            $if_err = true;
                            $rt_msg[$cus_is_in_id] ='子成员库存不足,库存'.$val['intsock_num'].'出库数'.$cus_is_in[$cus_is_in_id]['num'].'，组合'.implode(',',$cus_is_in[$cus_is_in_id]['cus']).'中有同个成员'.$val['group_custom_sku'];
                        }
                    }

                    if($if_err){
                        return ['code'=>500,'msg'=>implode("<br><br>",$rt_msg)];
                    }
       
                }

                foreach ($params['skuData'] as $val){
                    $val['location_id'] = 8;
                    if($params['type_detail']==17){
                        $detail['group_custom_sku'] = $val['custom_sku'];
                        $detail['group_custom_sku_id'] = $val['custom_sku_id'];
                        $detail['custom_sku'] = $val['group_custom_sku'];
                        $detail['custom_sku_id'] = $val['group_custom_sku_id'];
                        $val['custom_sku'] =  $detail['custom_sku'];
                        $val['custom_sku_id'] =  $detail['custom_sku_id'];
                        
                    }
                    if(isset($val['box_id'])){
                        //箱号
                        $detail['box_id'] = $val['box_id'];
                    }
                    if($val['num']==0){
                        //数量为0跳过此次循环
                        continue;
                    }


                    if($params['type_detail']==11){
                        //手工出库判断正确sku是否在系统存在
                        if(!empty($val['update_custom_sku'])){
                            $handwork = DB::table('self_custom_sku')->where('custom_sku',$val['update_custom_sku'])->orWhere('old_custom_sku',$val['update_custom_sku'])->select('spu_id','id','tongan_inventory','quanzhou_inventory','deposit_inventory','spu','custom_sku','old_custom_sku')->first();
                            if(empty($handwork)){
                                db::rollback();// 回调
                                return ['code'=>500,'msg'=>'系统没有'.$val['update_custom_sku']];
                            }
                        }
                    }

                    if ($params['type_detail'] == 9){
                        $detail['contract_no'] = $params['contract_no'] ?? '';
                    }

                    $customskus[] = $val['custom_sku'];
                    $detail['order_no'] = $transfers['order_no'];
                    $detail['custom_sku'] = $val['custom_sku'];
                    $spu = DB::table('self_custom_sku')->where('custom_sku',$val['custom_sku'])->orWhere('old_custom_sku',$val['custom_sku'])
                        ->select('spu','spu_id','cloud_num','id as custom_sku_id', 'tongan_inventory','quanzhou_inventory','deposit_inventory','type',
                            'base_spu_id','direct_inventory','shenzhen_inventory')->first();
                    $spu_json = json_decode(json_encode($spu),true);
                    if(!empty($spu)){

                        $oldspu = $this->GetOldSpu($spu->spu);
                        $balance = 0;//库存数量
                        $detail['spu'] = $oldspu;
                        $detail['spu_id'] = $spu->spu_id;
                        $detail['custom_sku_id'] = $spu->custom_sku_id;
                        
                        if($params['type_detail']>6&&$params['type_detail']<18){
                 
                            if($out_house==3&&$spu->type==2){
                                db::rollback();// 回调
                                return ['code'=>500,'msg'=>$val['custom_sku'].'云仓无法出库组合sku'];
                            }

                            // $balance = $spu_json[self::WAREHOUSE[$out_house]];
                            $inventoryType = 1;
                            if(isset($params['anomaly_order'])){
                                if($params['anomaly_order']=='次品出库'){
                                    $inventoryType=2;
                                }
                            }
                            $inventoryDetail = $this->inventoryPlatformDetail($spu->custom_sku_id,$out_house,[$transfers['platform_id']],$inventoryType);
                            $inventoryDetail = array_column($inventoryDetail, null, 'platform_id');

                            if(isset($inventoryDetail[$transfers['platform_id']])){

                                if($inventoryDetail[$transfers['platform_id']]['intsock_num']<intval($val['num'])){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'库存不足,只能出库'.$inventoryDetail[$transfers['platform_id']]['intsock_num']];
                                }
                            }
                        }
                    }else{
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'系统没有'.$val['custom_sku']];
                    }
                    $detail['createtime'] = $createtime;
                    $detail['transfers_num'] = $val['num'];
                    if($params['type_detail']==3){
                        //手工入库直接增加库位库存和仓库库存并增加资产
                        $detail['receive_num'] = $val['num'];
                        if(isset($val['location_id'])){
                            $location_num = DB::table('cloudhouse_location_num')->where('location_id',$val['location_id'])
                                ->where('custom_sku_id', $spu->custom_sku_id)->where('platform_id',$transfers['platform_id'])->select('id','num')->first();
                            if(!empty($location_num)){
                                $now_num = $location_num->num+$val['num'];
                                $update_location = DB::table('cloudhouse_location_num')->where('id',$location_num->id)->update(['num'=>$now_num,'update_time'=>time()]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'上架库位失败'];
                                }
                            }else{
                                $now_num = $val['num'];
                                $insert_location = DB::table('cloudhouse_location_num')->insert(['num'=>$now_num,'custom_sku_id'=>$spu->custom_sku_id,
                                    'custom_sku'=>$val['custom_sku'],'spu_id'=>$spu->spu_id,'spu'=>$spu->spu,'location_id'=>$val['location_id'],
                                    'platform_id'=>$transfers['platform_id'],'create_time'=>time()]);
                                if(!$insert_location){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'上架库位失败'];
                                }
                            }
                            $addlog = $this->add_location_log($val['location_id'],$val['num'],$val['custom_sku'],$spu->custom_sku_id,$oldspu,$spu->spu_id,1,$now_num,$transfers['order_no'],$user_id,$createtime);
                            if(!$addlog){
                                db::rollback();// 回调
                                return ['code'=>500,'msg'=>$val['custom_sku'].'新增库位库存变动日志失败'];
                            }
                        }else{
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'请选择库位'];
                        }
                        $this_balance = $spu_json[self::WAREHOUSE[$in_house]] + $val['num'];
                        $update_this[self::WAREHOUSE[$in_house]] = $this_balance;

                        if(isset($update_this)){
                            DB::table('self_custom_sku')->where('id',$spu->custom_sku_id)->update($update_this);
                        }

                        $query['warehouse_id'] = $in_house;
                        $query['custom_sku_id'] = $spu->custom_sku_id;
                        $query['price'] = $this->GetCloudHousePrice($in_house,$spu->custom_sku_id);
                        if($query['price']==0){
                            $priceData = DB::table('self_spu_info')->where('base_spu_id',$spu->base_spu_id)->select('unit_price')->first();
                            if(!empty($priceData)){
                                $query['price'] = $priceData->unit_price;
                            }
                        }
                        $query['num'] = $val['num'];
                        $query['user_id'] = $user_id;
                        $query['type'] = 2; //1为出2为入
                        $res = $this->UpCloudHousePrice($query);
                        if($res['type']!='success'){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'新增资产记录失败--'.$val['custom_sku']];
                        }

                        $insert['price'] =  $query['price'];
                        $insert['type_detail'] = $params['type_detail'];
                        $insert['custom_sku'] = $val['custom_sku'];
                        $insert['type'] = 2;
                        $insert['order_no'] = $transfers['order_no'];
                        $insert['num'] = $val['num'];
                        $insert['custom_sku_id'] = $spu->custom_sku_id;
                        $insert['spu_id'] =  $spu->spu_id;
                        $insert['spu'] =  $oldspu;
                        $insert['user_id'] =  $user_id;
                        $insert['createtime'] = $createtime;
                        $insert['warehouse_id'] = $in_house;
                        $insert['now_inventory'] = $this_balance;
                        $insert['now_total_price'] = $res['total_price'];
                        DB::table('cloudhouse_record')->insert($insert);

                    }
                    if($params['type_detail']==11){
                        //手工出库，盘点出库直接扣减库存，错色错码错款需要替换库存
                        $detail['receive_num'] = $val['num'];
                        $this_balance = $spu_json[self::WAREHOUSE[$out_house]] - $val['num'];//出库后剩余库存
                        $update_this[self::WAREHOUSE[$out_house]] = $this_balance;
                        if(isset($val['location_data'])){
                            foreach ($val['location_data'] as $locationVal){
                                $location_num = DB::table('cloudhouse_location_num')->where('custom_sku_id', $spu->custom_sku_id)->where('location_id',$locationVal['location_id'])
                                    ->where('platform_id',$locationVal['platform_id'])->select('location_id', 'num','platform_id','id')->first();
                                if(!$location_num){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'可用库存不足,平台：'.$locationVal['platform_id'].'库位：'.$locationVal['location_id']];
                                }

                                $lock_data = $this->lock_inventory_d($spu->custom_sku_id,$locationVal['platform_id'],$locationVal['location_id']);
                                if(isset($lock_data[$spu->custom_sku_id][$locationVal['location_id']][$locationVal['platform_id']])){
                                    $lock_num = $lock_data[$spu->custom_sku_id][$locationVal['location_id']][$locationVal['platform_id']];
                                }else{
                                    $lock_num = 0;
                                }
                                $instock_num = $location_num->num - $lock_num;
                                if($instock_num<$locationVal['num']){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'可用库存不足,平台：'.$locationVal['platform_id'].'库位：'.$locationVal['location_id']];
                                }
                                $now_num = $location_num->num-$locationVal['num'];
                                $update_location = DB::table('cloudhouse_location_num')->where('id',$location_num->id)->update(['num'=>$now_num,'update_time'=>time()]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'下架库位失败'];
                                }
                                $addlog = $this->add_location_log($locationVal['location_id'],$locationVal['num'],$val['custom_sku'],$spu->custom_sku_id,$oldspu,
                                    $spu->spu_id,2,$now_num,$transfers['order_no'],$user_id,$createtime,$locationVal['platform_id']);
                                if(!$addlog){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'新增库位库存变动日志失败'];
                                }
                            }
                        }else{
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'请选择库位'];
                        }

                        if(isset($handwork)){
                            $handwork = json_decode(json_encode($handwork),true);
                            if($spu->custom_sku_id==$handwork['id']){
                                db::rollback();// 回调
                                return ['code'=>500,'msg'=>$val['custom_sku'].'正确商品sku不能与原sku一致'];
                            }
                            $handwork_balance = $handwork[self::WAREHOUSE[$out_house]] + $val['num'];
                            $update_handwork[self::WAREHOUSE[$out_house]] = $handwork_balance;
                        }

                        if(isset($update_handwork)){
                            DB::table('self_custom_sku')->where('id',$handwork['id'])->update($update_handwork);
                        }
                        if(isset($update_this)){
                            DB::table('self_custom_sku')->where('id',$spu->custom_sku_id)->update($update_this);
                        }

                        $query['warehouse_id'] = $out_house;
                        $query['custom_sku_id'] = $spu->custom_sku_id;
                        $query['price'] = $this->GetCloudHousePrice($out_house,$spu->custom_sku_id);
                        $query['num'] = $val['num'];
                        $query['user_id'] = $user_id;
                        $query['type'] = 1; //1为出2为入
                        $res = $this->UpCloudHousePrice($query);
                        if($res['type']!='success'){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'新增资产记录失败--'.$val['custom_sku']];
                        }

                        $insert['price'] = $query['price'];
                        $insert['type_detail'] = $params['type_detail'];
                        $insert['custom_sku'] = $val['custom_sku'];
                        $insert['type'] = 1;
                        $insert['order_no'] = $transfers['order_no'];
                        $insert['num'] = $val['num'];
                        $insert['custom_sku_id'] = $spu->custom_sku_id;
                        $insert['spu_id'] =  $spu->spu_id;
                        $insert['spu'] =  $oldspu;
                        $insert['user_id'] =  $user_id;
                        $insert['createtime'] = $createtime;
                        $insert['warehouse_id'] = $out_house;
                        $insert['now_inventory'] = $this_balance;
                        $insert['now_total_price'] = $res['total_price'];
                        DB::table('cloudhouse_record')->insert($insert);
                        if(isset($handwork)){
                            $query['warehouse_id'] = $out_house;
                            $query['custom_sku_id'] = $handwork['id'];
                            $query['price'] = $this->GetCloudHousePrice($out_house,$handwork['id']);
                            if($query['price']==0){
                                $priceData = DB::table('self_spu_info')->where('base_spu_id',$spu->base_spu_id)->select('unit_price')->first();
                                if(!empty($priceData)){
                                    $query['price'] = $priceData->unit_price;
                                }
                            }
                            $query['num'] = $val['num'];
                            $query['user_id'] = $user_id;
                            $query['type'] = 2; //1为出2为入
                            $res = $this->UpCloudHousePrice($query);
                            if($res['type']!='success'){
                                db::rollback();// 回调
                                return ['code'=>500,'msg'=>'新增资产记录失败--'.$val['custom_sku']];
                            }

                            $insert['price'] = $query['price'];
                            $insert['type'] = 2;
                            $insert['type_detail'] = 3;
                            $insert['custom_sku_id'] = $handwork['id'];
                            $insert['spu_id'] = $handwork['spu_id'];
                            $insert['spu'] = $handwork['spu'];
                            $insert['user_id'] =  $user_id;
                            $insert['now_inventory'] = $handwork_balance;
                            $insert['now_total_price'] = $res['total_price'];
                            if($handwork['old_custom_sku']){
                                $insert['custom_sku'] = $handwork['old_custom_sku'];
                            }else{
                                $insert['custom_sku'] = $handwork['custom_sku'];
                            }
                            DB::table('cloudhouse_record')->insert($insert);
                            foreach ($val['location_data'] as $locationVal){
                                $location_num = DB::table('cloudhouse_location_num')->where('location_id',$val['update_location_id'])->where('custom_sku_id',
                                    $handwork['id'])->where('platform_id',$locationVal['platform_id'])->select('id','num')->first();
                                if(!empty($location_num)){
                                    $now_num = $location_num->num+$locationVal['num'];
                                    $update_location = DB::table('cloudhouse_location_num')->where('id',$location_num->id)->update(['num'=>$now_num,'update_time'=>time()]);
                                    if(!$update_location){
                                        db::rollback();// 回调
                                        return ['code'=>500,'msg'=>$val['custom_sku'].'上架库位失败'];
                                    }
                                }else{
                                    $now_num = $locationVal['num'];
                                    $insert_location = DB::table('cloudhouse_location_num')->insert(['num'=>$now_num,
                                        'platform_id'=>$locationVal['platform_id'],'custom_sku_id'=>$handwork['id'],'custom_sku'=>$insert['custom_sku'],
                                        'spu_id'=>$handwork['spu_id'], 'spu'=>$handwork['spu'],'location_id'=>$val['update_location_id'],'create_time'=>time()]);
                                    if(!$insert_location){
                                        db::rollback();// 回调
                                        return ['code'=>500,'msg'=>$val['custom_sku'].'上架库位失败'];
                                    }
                                }
                                $addlog = $this->add_location_log($val['update_location_id'],$val['num'],$insert['custom_sku'],$handwork['id'],$handwork['spu'],
                                    $handwork['spu_id'],1,$now_num,$transfers['order_no'],$user_id,$createtime,$locationVal['platform_id']);
                                if(!$addlog){
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>$val['custom_sku'].'新增库位库存变动日志失败'];
                                }
                            }
                        }
                    }//手工出库结束

                    // if($spu->type==2){
                    //     if($groupsku){
                    //         foreach ($groupsku as $g){
                    //             $detail['custom_sku'] = $g['group_custom_sku'];
                    //             $groupSkuData = $this->GetCustomSkuId($g['group_custom_sku_id']);
                    //             $detail['spu'] = $groupSkuData['spu'];
                    //             $detail['spu_id'] = $groupSkuData['spu_id'];
                    //             $detail['custom_sku_id'] = $g['group_custom_sku_id'];
                    //             $total_num += $val['num'];
                    //             $insert_detail = DB::table('goods_transfers_detail')->insert($detail);
                    //         }
                    //     }else{
                    //         return ['code'=>500,'msg'=>'获取'.$val['custom_sku'].'的子sku失败'];
                    //     }
                    // }else{
                        $total_num += intval($val['num']);
                        $insert_detail = DB::table('goods_transfers_detail')->insert($detail);
                    // }


                    if (isset($lxParams) && isset($insert)) {
                        $lxParams['wid']            = $insert['warehouse_id'];
                        $lxParams['type']           = $insert['type'] == 1 ? 11 : 1;
                        $lxParams['product_list'][] = [
                            'sku'      => DB::table('self_custom_sku')->where('id', $insert['custom_sku_id'])->value('custom_sku'),
                            'good_num' => $insert['num'],
                        ];
                    }

                }

                //计算调拨数量总数修改调拨数据
                if($params['type_detail']==11||$params['type_detail']==3){
                    $update =  DB::table('goods_transfers')->where('id',$transfers_id)->update(['total_num'=>$total_num,'is_push'=>3,'sj_arrive_time'=>$createtime]);
                    if(!$update){
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'修改状态失败'];
                    }
                }elseif($params['type_detail']==9){
//                    $update =  DB::table('goods_transfers')->where('id',$transfers_id)->update(['total_num'=>$total_num,'is_push'=>2]);
                    $update2 =  DB::table('goods_transfers_box')->where('id',$box_id)->update(['box_num'=>$total_num]);
                    $contractNo[] = $params['contract_no'];
                    $update =  DB::table('goods_transfers')->where('id',$transfers_id)->update(['contract_no' => json_encode($contractNo)]);
                }else{
                    $update =  DB::table('goods_transfers')->where('id',$transfers_id)->update(['total_num'=>$total_num]);
                }
                if($in_house==3){
                    //同步商品信息到云仓
                    $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                    try {
                        $cloud::sendJob($customskus);
                    } catch(\Exception $e){
                        db::rollback();// 回调
                        Redis::Lpush('send_goods_fail',json_encode($params));
                    }
                }

                //同步库存到领星
                if (isset($lxParams) && count($lxParams['product_list']) > 0 && isset($insert)) {
                    $data = [
                        'fun'    => $lxParams['type'] == 1 ? 'addInStorageOrder' : 'addOutStorageOrder',
                        'params' => $lxParams,
                    ];
                    //加入同步库存到翎星队列
                    $job = new LingXingJob($data);
                    $job->dispatch($data)->onQueue('ling_xing');
                }

                db::commit();

                return ['code'=>200,'msg'=>'提交成功','order_no'=>$transfers['order_no'],'id'=>$transfers_id];
            }else{
                db::rollback();// 回调
                return ['code'=>500,'msg'=>'新增失败'];
            }
        }else{
            db::rollback();// 回调
            return ['code'=>500,'msg'=>'数据类型错误'];
        }
    }

    //包装袋管理
    public function GetBoxCodeList($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页 
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }


        $list = db::table('goods_transfers_box_detail as a')->leftjoin('goods_transfers_box as b','b.id','=','a.box_id')->select('a.custom_sku','a.box_num','a.shelf_num','b.box_code','b.box_num as all_num');



        if(isset($params['box_code'])){
            $list = $list->where('b.box_code',$params['box_code']);
        }

        $count = $list->count();
        $list = $list->offset($pagenNum)
        ->limit($limit)
        ->get();


        return ['data'=>$list,'total_num'=>$count];
    }


    
    //压缩包管理
    public function GetBoxCodeYsList($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页 
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->where('type_detail',25);
        // if(isset($params['box_code'])){
        //     $list = $list->where('box_code','like','%'.$params['box_code'].'%');
        // }
        if(isset($params['order_no'])){
            $list = $list->where('order_no',$params['order_no']);
        }
        
        $count = $list->count();
        $list = $list->offset($pagenNum)
        ->limit($limit)
        ->get();


        foreach ($list as $v) {
            # code...
            $box_codes = explode(',',$v->box_code);
            $v->detail = [];
            if(is_array($box_codes)){
                $v->detail = db::table('goods_transfers_box_detail as a')->leftjoin('goods_transfers_box as b','b.id','=','a.box_id')->whereIn('b.box_code',$box_codes)->select('a.custom_sku','a.box_num','a.shelf_num','b.box_code','b.box_num as all_num')->get();       
            }
        }

        return ['data'=>$list,'total_num'=>$count];
    }



    public function goods_transfers_back($params){
        $token = $params['token'];

        if(empty($params['skuData'])){
            return ['code'=>500,'msg'=>'请选择要调动的商品'];
        }

        if(empty($params['in_house'])){
            return ['code'=>500,'msg'=>'请选择入仓仓库'];
        }

        if(empty($params['yj_arrive_time'])){
            return ['code'=>500,'msg'=>'请填写预计到达时间'];
        }

        $user_data = DB::table('users')->where('token', '=', $token)->select('Id', 'account')->get();
        $user_id = $user_data[0]->Id;
        $createtime = date('Y-m-d H:i:s');



        if(is_array($params['skuData'])){
            $transfers['back_order_no'] = $params['back_order_no']??'';
            $transfers['order_no'] = rand(100,999).time();
            $transfers['total_num'] = 0;
            $transfers['sku_count'] = count($params['skuData']);
            $transfers['out_house'] = $params['out_house'];
            $transfers['in_house'] = $params['in_house'];
            $transfers['type'] = $params['type'];
            $transfers['yj_arrive_time'] = $params['yj_arrive_time'];
            $transfers['type_detail'] = $params['type_detail'];
            $transfers['address'] = isset($params['address'])? $params['address'] : '';
            $transfers['user_id'] = $user_id;
            $transfers['text'] = isset($params['remark']) ? $params['remark'] : '';
            $transfers['createtime'] = $createtime;
            $transfers['shop_id'] = isset($params['shop_id'])? $params['shop_id'] : 0;
            $transfers['platform_id'] = $params['platform_id'];
            $transfers['delivery_time'] = date('Y-m-d H:i:s'); // 采购退回出库时间
            $total_num = 0;

            //生成调拨数据
            db::beginTransaction();    //开启事务
            $transfers_id = DB::table('goods_transfers')->insertGetId($transfers);

            if($params['type_detail']==7||$params['type_detail']==9){
                $box_id = $this->Addbox($transfers['order_no'],$transfers['out_house']);
                if(!$box_id){
                    db::rollback();// 回调
                    return ['code'=>500,'msg'=>'生成中转箱任务失败'];
                }
            }
//            $customskus = array();
            if($transfers_id){
                $contract_no = array();
                foreach ($params['skuData'] as $val){
                    if(!empty($val['contract_no'])){
                        $contract_no[] = $val['contract_no'];
                        $detail['contract_no'] = $val['contract_no'];
                    }
//                    $customskus[] = $val['custom_sku'];
                    $detail['order_no'] = $transfers['order_no'];
                    $detail['custom_sku'] = $val['custom_sku'];
                    $spu = DB::table('self_custom_sku')->where('custom_sku',$val['custom_sku'])->orWhere('old_custom_sku',$val['custom_sku'])->select('spu','spu_id','cloud_num','id as custom_sku_id','tongan_inventory','quanzhou_inventory','deposit_inventory')->first();
                    if(!empty($spu)){
                        $oldspu = $this->GetOldSpu($spu->spu);
                        $balance = 0;//库存数量
                        $balance_num = 0;//预减后库存数量
                        if($params['out_house']==1){
                            $balance = $spu->tongan_inventory;
                        }elseif($params['out_house']==2){
                            $balance = $spu->quanzhou_inventory;
                        }elseif($params['out_house']==3){
                            $balance = $spu->cloud_num;
                        }elseif($params['out_house']==6){
                            $balance = $spu->deposit_inventory;
                        }else{
                            $receive = DB::table('goods_transfers_detail')->where('order_no',$params['back_order_no'])->where('custom_sku_id',$spu->custom_sku_id)->select('receive_num')->first();
                            if(!empty($receive)){
                                $balance = $receive->receive_num;
                            }
                            if($params['type_detail']==5){
                                $orders = db::table('fpx_order')->where('out_no', $params['back_order_no'])->first();
                                if($orders){
                                    $del['user_id'] = $user_id;
                                    $del['order_id'] =  $orders->order_id;
                                    $del['create_time'] = $createtime;
                                    db::table('fpx_del_order')->insert($del);
                                    db::table('fpx_order')->where('id', $orders->id)->update(['status'=>-1]);
                                }
                            }
                        }
//                        if($params['type_detail']!=1&&$params['type_detail']!=9){
//                            $request = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
//                                ->whereIn('a.is_push',[1,2,4])
//                                ->where('b.custom_sku_id',$spu->custom_sku_id)
//                                ->where('a.out_house',$params['out_house'])
//                                ->select('b.transfers_num')
//                                ->get();
//                            $request_num = 0;
//                            if(!empty($request)&&$params['type_detail']!=11){
//                                foreach ($request as $r){
//                                    $request_num += $r->transfers_num;
//                                }
//                                $balance_num = $balance-$request_num;
//                            }else{
//                                $balance_num = $balance;
//                            }
//                            if($balance_num<$val['num']){
//                                db::rollback();// 回调
//                                return ['code'=>500,'msg'=>$val['custom_sku'].'库存不足'];
//                            }
//                        }
                        if($params['type_detail']==9){
                            //采购退回出库，人工选择多个库位对应多个数量
                            if($params['out_house']!=3){

                                if(isset($val['location_data'])){
                                    $box_total_num = 0;
                                    foreach ($val['location_data'] as $locationVal){
                                        $location_num = DB::table('cloudhouse_location_num')->where('location_id',$locationVal['location_id'])->where('custom_sku_id',
                                            $spu->custom_sku_id)->where('platform_id',$transfers['platform_id'])->select('location_id','num','id')->first();
                                        if(empty($location_num)){
                                            db::rollback();// 回调
                                            return ['code'=>500,'msg'=>$locationVal['location_id'].'没有'.$val['custom_sku'].'的库存数据'];
                                        }
                                        $lock = $this->lock_inventory_d($spu->custom_sku_id,$transfers['platform_id'],$locationVal['location_id']);

                                        if(isset($lock[$spu->custom_sku_id][$locationVal['location_id']][$transfers['platform_id']])){
                                            $lock_num = $lock[$spu->custom_sku_id][$locationVal['location_id']][$transfers['platform_id']];
                                        }else{
                                            $lock_num = 0;
                                        }

                                        $instock_num = $location_num->num - $lock_num;
                                        if($instock_num<$locationVal['num']){
                                            db::rollback();// 回调
                                            return ['code'=>500,'msg'=>$val['custom_sku'].'可用库存不足,平台：'.$params['platform_id'].'库位：'.$locationVal['location_id']];
                                        }
                                        $add_box_data = DB::table('goods_transfers_box_detail')->insert(['box_id'=>$box_id,'custom_sku'=>$val['custom_sku'],'custom_sku_id'=>$spu->custom_sku_id,'box_num'=>$locationVal['num'],'location_ids'=>$locationVal['location_id']]);
                                        if(!$add_box_data){
                                            db::rollback();// 回调
                                            return ['code'=>500,'msg'=>$val['custom_sku'].'新增中转箱数据失败'];
                                        }
                                        $box_total_num+=$locationVal['num'];
                                    }
                                    DB::table('goods_transfers_box')->where('order_no',$transfers['order_no'])->update(['box_num'=>$box_total_num]);

                                }else{
                                    db::rollback();// 回调
                                    return ['code'=>500,'msg'=>'请选择库位'];
                                }
                            }else{

                            }
                        }
                        $detail['spu'] = $oldspu;
                    }else{
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'系统没有'.$val['custom_sku']];
                    }
                    $detail['createtime'] = $createtime;
                    $detail['transfers_num'] = $val['num'];
                    $detail['spu_id'] = $spu->spu_id;
                    $detail['custom_sku_id'] = $spu->custom_sku_id;
                    if(isset($val['box_id'])){
                        $detail['box_id'] = $val['box_id'];
                    }
                    $total_num += $val['num'];
                    $insert_detail = DB::table('goods_transfers_detail')->insert($detail);
                }
                $contract_no = array_unique($contract_no);
                $contract_no = json_encode($contract_no);
                //计算调拨数量总数修改调拨数据
                if($params['type_detail']==9){
                    $update = DB::table('goods_transfers')->where('id',$transfers_id)->update(['total_num'=>$total_num,'contract_no'=>$contract_no,'is_push'=>2]);
                }else{
                    $update = DB::table('goods_transfers')->where('id',$transfers_id)->update(['total_num'=>$total_num,'contract_no'=>$contract_no]);
                }

//                $quequeres['order_no'] =  $transfers['order_no'];
//                $quequeres['detail'] = $params['skuData'];
//                if ($params['in_house'] == 3) {
//                    $quequeres['type'] = 'DBRK';
//                    $quequeres['text'] = $transfers['text'];
//                    //云仓则加入队列
//                    $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
//                    try {
//                        $cloud::inhouseJob($quequeres);
//                    } catch (\Exception $e) {
//                        Redis::Lpush('in_house_fail', json_encode($quequeres));
//                    }
//                }
//                if ($params['out_house'] == 3) {
//                    $quequeres['type'] = 'PTCK';
//                    $quequeres['text'] = $transfers['text'];
//                    //云仓则加入队列
//                    $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
//                    try {
//                        $cloud::outhouseJob($quequeres);
//                    } catch (\Exception $e) {
//                        Redis::Lpush('in_house_fail', json_encode($quequeres));
//                    }
//                }
                db::commit();
                return ['code'=>200,'msg'=>'提交成功'];
            }else{
                db::rollback();// 回调
                return ['code'=>500,'msg'=>'提交失败'];
            }
        }else{
            db::rollback();// 回调
            return ['code'=>500,'msg'=>'数据类型错误'];
        }
    }





    public function transfers_data($params){
        $type = isset($params['type']) ? $params['type'] : 1;
        $type_detail = isset($params['type_detail']) ? $params['type_detail'] : 1;
        $list = DB::table('goods_transfers as a')->whereIn('a.type',$type)->where('a.type_detail',$type_detail);

        if (isset($params['id']) && is_array($params['id'])){
            $list = $list->whereIn('a.id', $params['id']);
        }

        if(isset($params['amazon_order_id'])){
            $fpx_order_res = db::table('fpx_order')->where('order_id','like','%'.$params['amazon_order_id'].'%')->get()->toarray();
            if($fpx_order_res){
                $order_nos = array_column($fpx_order_res,'out_no');
                $list = $list->whereIn('a.order_no', $order_nos);
            }
        }

        if(!empty($params['in_house'])){
            $list = $list->whereIn('a.in_house',$params['in_house']);
        }

        if(!empty($params['out_house'])){
            $list = $list->whereIn('a.out_house',$params['out_house']);
        }

        if(!empty($params['platform_id'])){
            // $list = $list->whereIn('platform_id',$params['platform_id']);
//            $shop_res = db::table('shop')->whereIn('platform_id',$params['platform_id'])->get()->toArray();
//            $shop_ids = array_column($shop_res,'Id');
            $list = $list->whereIn('a.platform_id',$params['platform_id']);
        }
//        if (empty($params['is_amazon'])){
//            $shop_res = db::table('shop')->whereIn('a.platform_id', 5)->get();
//            $shop_res = json_decode(json_encode($shop_res), true);
//            $shop_ids = array_column($shop_res,'Id');
//            $list = $list->whereIn('a.shop_id',$shop_ids);
//        }

        if(!empty($params['order_no'])){
            $list = $list->where('a.order_no','like','%'.$params['order_no'].'%');
        }

        if(!empty($params['contract_no'])){
            $list = $list->where('a.contract_no','like','%'.$params['contract_no'].'%');
        }

        if(!empty($params['custom_sku'])){
            $custom_sku = db::table('self_custom_sku')
                ->where('custom_sku', 'like', '%'.$params['custom_sku'].'%')
                ->orWhere('old_custom_sku', 'like', '%'.$params['custom_sku'].'%')
                ->get(['Id']);
            $custom_sku = json_decode(json_encode($custom_sku),true); 
            $custom_sku_id = array_column($custom_sku, 'Id');
            $detail = DB::table('goods_transfers_detail')->whereIn('custom_sku_id',$custom_sku_id)->select('order_no')->distinct()->get();
            $detail = json_decode(json_encode($detail),true);
            $order_no_arr = array_column($detail,'order_no');
            if(!empty($order_no_arr)){
                $list = $list->whereIn('a.order_no',$order_no_arr);
            }
        }

        if(!empty($params['custom_sku_name'])){
            $custom_sku = db::table('self_custom_sku')
                ->where('name', 'like', '%'.$params['custom_sku_name'].'%')
                ->get(['Id']);
            $custom_sku = json_decode(json_encode($custom_sku),true); 
            $custom_sku_id = array_column($custom_sku, 'Id');
            $detail = DB::table('goods_transfers_detail')->whereIn('custom_sku_id',$custom_sku_id)->select('order_no')->distinct()->get();
            $detail = json_decode(json_encode($detail),true);
            $order_no_arr = array_column($detail,'order_no');
            if(!empty($order_no_arr)){
                $list = $list->whereIn('a.order_no',$order_no_arr);
            }
        }

        if(!empty($params['spu'])){
            $spu_id = $this->GetSpuId($params['spu']);
            $detail = DB::table('goods_transfers_detail')->where('spu_id',$spu_id)->select('order_no')->distinct()->get();
            $detail = json_decode(json_encode($detail),true);
            $order_no_arr = array_column($detail,'order_no');
            $list = $list->whereIn('a.order_no',$order_no_arr);
        }

        if (!empty($params['supplier_id'])) {
            $contractNos = DB::table('cloudhouse_contract_total')->where('supplier_id', $params['supplier_id'])->select('contract_no')->get()->pluck('contract_no');
            if (!$contractNos->count()) {
                return ['data' => [], 'totalNum' => 0];
            }
            $orderNos = DB::table('goods_transfers_detail')->whereIn('contract_no', $contractNos)->select('order_no')->get()->pluck('order_no');
            if (!$orderNos->count()) {
                return ['data' => [], 'totalNum' => 0];
            }
            $list->whereIn('order_no', $orderNos);
        }

        if(!empty($params['user_id'])){
            $list = $list->where('a.user_id',$params['user_id']);
        }

        if(!empty($params['status'])){
            $list = $list->where('a.is_push',$params['status']);
        }

        if(!empty($params['box_num'])){
            $list = $list->where('a.box_num',$params['box_num']);
        }

        if(!empty($params['is_qc'])){
            $list = $list->where('a.is_qc',$params['is_qc']);
        }

        if(!empty($params['remark'])){
            $list = $list->where('a.text','like','%'.$params['remark'].'%');
        }

        if(!empty($params['start_time'])&&!empty($params['end_time'])){
            $list = $list->whereBetween('a.createtime', [$params['start_time'], $params['end_time']]);
        }

        if(isset($params['sj_arrive_time']) && is_array($params['sj_arrive_time'])){
            $list = $list->whereBetween('a.sj_arrive_time', [$params['sj_arrive_time'][0], date('Y-m-d', strtotime($params['sj_arrive_time'][1])).' 23:59:59']);
        }

        $count=$list->count();//数据总数

        if ((isset($params['page']) || isset($params['limit'])) && !isset($params['posttype'])){
            $page = isset($params['page']) ? $params['page'] : 1;
            $limit = isset($params['limit']) ? $params['limit'] : 30;
            //分页
            $pagenNum=$page-1;
            if ($pagenNum != 0) {
                $pagenNum = $limit * $pagenNum;
            }
            $list = $list
                ->offset($pagenNum)
                ->limit($limit);
        }

         DB::connection()->enableQueryLog();


        //执行查询
        $data = $list
            ->orderBy('a.createtime','desc')
            ->get()
            ->toArray();

        $contractMdl = db::table('cloudhouse_contract_total')
            ->get(['contract_no', 'purchase_order_no'])
            ->keyBy('contract_no');
        $alibabaMdl = db::table('alibaba_order_item')
            ->get(['order_id', 'logisticsBillNo', 'logisticsCode']);
        $alibabaList = [];
        foreach ($alibabaMdl as $_v){
            $alibabaList[$_v->order_id][] = $_v->logisticsBillNo;
        }
//         var_dump(DB::getQueryLog());
        $warehouseMdl = db::table('cloudhouse_warehouse')
            ->get(['id', 'warehouse_name'])
            ->keyBy('id');

        foreach ($data as $v){
            $attr = json_decode($v->attr,true);
            $v->attrs =  $attr;
            $purchaseNo = [];
            $logisticsCode = [];
            $logisticsBillNo = [];
            $v->supplier_name = [];
            $v->contract_no_string = '';
            $v->supplier_name_string = '';
            if($v->contract_no){
                $contract_no = json_decode($v->contract_no,true);
                foreach ($contract_no as $cno){
                    if (!isset($contractMdl[$cno])){
                        continue;
                    }
                    if (!empty($contractMdl[$cno]->purchase_order_no)){
                        $purchaseNo[] = $contractMdl[$cno]->purchase_order_no;
                        if (isset($alibabaList[$contractMdl[$cno]->purchase_order_no])){
                            $logisticsBillNo = array_merge($logisticsBillNo, $alibabaList[$contractMdl[$cno]->purchase_order_no]);
                        }
                    }
                }

                $supplier = DB::table('cloudhouse_contract_total')->whereIn('contract_no',$contract_no)->select('supplier_short_name')->get();
                $supplier = json_decode(json_encode($supplier),true);
                $v->supplier_name = array_column($supplier,'supplier_short_name');
                $v->supplier_name = array_unique($v->supplier_name);
                $v->contract_no_string = implode(',', json_decode($v->contract_no, true));
                $v->supplier_name_string = implode(',', $v->supplier_name);
            }
            $v->purchase_order_no = array_unique($purchaseNo);
            $v->purchase_order_no_string = implode(',', $v->purchase_order_no);
            $v->logistics_code = array_unique($logisticsBillNo);
            $v->logistics_code_string = implode(',', $v->logistics_code);
            $v->logisticsBillNo = array_unique($logisticsBillNo);
//            if($v->shop_id){
//                $shop_data = $this->GetShop($v->shop_id);
//                if($shop_data){
//                    $v->shop_name = $shop_data['account'];
//                    $platform = $this->GetPlatform($shop_data['platform_id']);
//                    if($platform){
//                        $v->platform = $platform['name'];
//                    }
//                }
//            }

            if($v->platform_id){
                $platform = $this->GetPlatform($v->platform_id);
                if($platform){
                    $v->platform = $platform['name'];
                }
            }

            if($v->receive_platform_id){
                $receive_platform = $this->GetPlatform($v->receive_platform_id);
                if($receive_platform){
                    $v->receive_platform = $receive_platform['name'];
                }
            }

            $account = $this->GetUsers($v->user_id);
            $confirm = $this->GetUsers($v->confirm_id);
            if($account){
                $v->account = $account['account'];
            }
            if($confirm){
                $v->confirm_user = $confirm['account'];
            }
            $v->file_url = json_decode($v->file_url, true) ?? [];
            $v->img_url = json_decode($v->img_url, true) ?? [];
//            $v->contract_no = json_decode($v->contract_no, true) ?? [];
            $v->is_qc = $v->is_qc == 1 ? '是':'否';
            $v->is_push_name = Constant::GOODS_TRANSFERS_IS_PUSH[$v->is_push] ?? '';
            $v->in_house_name = '';
            if(isset($warehouseMdl[$v->in_house])){
                $v->in_house_name = $warehouseMdl[$v->in_house]->warehouse_name;
            }
      
            $v->out_house_name  = '';
            if(isset($warehouseMdl[$v->out_house])){
                $v->out_house_name = $warehouseMdl[$v->out_house]->warehouse_name;
            }
          
            $v->is_export_name = $v->is_export == 1 ? '异常':'正常';
            $v->supplier_name = array_values($v->supplier_name);
            $v->type_detail_name = Constant::GOODS_TRANSFERS_TYPE_DETAIL[$v->type_detail] ?? '';


            // if(!empty($v->attr)){
            //     $attr = json_decode($v->attr,true);
            // }
           
            $v->m_title = '';
            if(isset($attr['m_title'])){
                $v->m_title = $attr['m_title'];
            }

            $v->long = '';
            if(isset($attr['long'])){
                $v->long = $attr['long'];
            }

            $v->width = '';
            if(isset($attr['width'])){
                $v->width = $attr['width'];
            }

            $v->height = '';
            if(isset($attr['height'])){
                $v->height = $attr['height'];
            }

            $v->weight = '';
            if(isset($attr['weight'])){
                $v->weight = $attr['weight'];
            }

            $v->desc = '';
            if(isset($attr['desc'])){
                $v->desc = $attr['desc'];
            }

            
            $v->img_url = [];
            if(isset($attr['photo'])){
                $v->img_url = json_decode($attr['photo'],true);
            }

            $v->cus_weight = 0;
            $cus =  db::table('goods_transfers_detail as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->where('a.order_no',$v->order_no)->select('a.receive_num','b.weight')->get();

            foreach ($cus as $csv) {
                # code...
                $v->cus_weight+=$csv->receive_num * $csv->weight;
            }

            $v->cus_weight = round( $v->cus_weight,2);
            $v->pack_num = db::table('goods_transfers_detail')->where('order_no',$v->order_no)->sum('pack_num');
            $v->save_num = db::table('goods_transfers_detail')->where('order_no',$v->order_no)->sum('save_num');

            $v->pdf_url = '/pc/inventory/save_ys_pdf?order_no='.$v->order_no;
            $v->ewm_url = 'http://116.62.169.253:9080/qrcode/'.$v->order_no.'.png?id='.rand(1,1000);
        }

        // 导出明细
        $posttype = $params['posttype'] ?? 1;
        if ($posttype == 2){
            $title = '';
            if (isset($params['type_detail'])){
                $title = Constant::GOODS_TRANSFERS_TYPE_DETAIL[$params['type_detail']] ?? '出入库';
            }
            $p['title'] = $title.'导出'.time();
            if ($type_detail == 7){
                $titleName = '调拨入库单号';
            }else{
                $titleName = '退回单号';
            }
            $p['title_list']  = [
                'order_no' => '订单号',
                'type_detail_name' => '出入库类型',
                'is_push_name'=>'状态',
                'is_qc'=>'是否质检',
                'back_order_no'=>$titleName,
                'contract_no_string'=>'采购单号',
                'platform'=>'国家',
                'sku_count'=>'sku数量',
                'total_num'=>'总数',
                'receive_total_num'=>'实际接收总数',
                'in_house_name'=>'入仓仓库',
                'out_house_name'=>'出仓仓库',
                'is_export_name'=>'是否异常',
                'yj_arrive_time'=>'预计到达时间',
                'sj_arrive_time'=>'入库时间',
                'supplier_name_string' => '供应商',
                'account'=>'操作人',
                'confirm_user'=>'确认人',
                'createtime'=>'创建时间',
                'anomaly_order'=>'异常单号',
                'text'=>'备注',
            ];
            $p['data'] = $data;
//                $this->excel_expord($p);

            $p['data'] =  $data;
            $p['user_id'] = $params['export_user_id'];
            $p['type'] = $title.'导出';
//                return $this->publicExport($p);
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => '500', 'msg' => '加入队列失败'];
            }
            return ['type' => '200','msg' => '加入队列成功'];
        }
        if ($posttype == 3){
//            $orderNos = [];
//            foreach ($data as $_v){
//                $orderNos[] = $_v->order_no;
//            }
//            return $this->transfers_data_detail(['posttype' => 2, 'order_no' => $orderNos, 'find_user_id' => $params['export_user_id']]);
            $list = DB::table('goods_transfers_detail as a');
            if (isset($params['id']) && is_array($params['id'])){
                $list = $list->whereIn('e.id', $params['id']);
            }

            if(isset($params['amazon_order_id'])){
                $fpx_order_res = db::table('fpx_order')->where('order_id','like','%'.$params['amazon_order_id'].'%')->get()->toarray();
                if($fpx_order_res){
                    $order_nos = array_column($fpx_order_res,'out_no');
                    $list = $list->whereIn('a.order_no', $order_nos);
                }
            }

            if(!empty($params['in_house'])){
                $list = $list->whereIn('e.in_house',$params['in_house']);
            }

            if(!empty($params['out_house'])){
                $list = $list->whereIn('e.out_house',$params['out_house']);
            }

            if(!empty($params['platform_id'])){
                // $list = $list->whereIn('platform_id',$params['platform_id']);
                $shop_res = db::table('shop')->whereIn('platform_id',$params['platform_id'])->get()->toArray();
                $shop_ids = array_column($shop_res,'Id');
                $list = $list->whereIn('e.shop_id',$shop_ids);
            }
//        if (empty($params['is_amazon'])){
//            $shop_res = db::table('shop')->whereIn('a.platform_id', 5)->get();
//            $shop_res = json_decode(json_encode($shop_res), true);
//            $shop_ids = array_column($shop_res,'Id');
//            $list = $list->whereIn('a.shop_id',$shop_ids);
//        }

            if(!empty($params['order_no'])){
                $list = $list->where('a.order_no','like','%'.$params['order_no'].'%');
            }

            if(!empty($params['contract_no'])){
                $list = $list->where('a.contract_no','like','%'.$params['contract_no'].'%');
            }

            if(!empty($params['custom_sku'])){
                $custom_sku_id = $this->GetCustomSkuId($params['custom_sku']);
                $detail = DB::table('goods_transfers_detail')->where('custom_sku_id',$custom_sku_id)->select('order_no')->distinct()->get();
                $detail = json_decode(json_encode($detail),true);
                $order_no_arr = array_column($detail,'order_no');
                if(!empty($order_no_arr)){
                    $list = $list->whereIn('a.order_no',$order_no_arr);
                }
            }

            if(!empty($params['spu'])){
                $spu_id = $this->GetSpuId($params['spu']);
                $detail = DB::table('goods_transfers_detail')->where('spu_id',$spu_id)->select('order_no')->distinct()->get();
                $detail = json_decode(json_encode($detail),true);
                $order_no_arr = array_column($detail,'order_no');
                $list = $list->whereIn('a.order_no',$order_no_arr);
            }

            if (!empty($params['supplier_id'])) {
                $contractNos = DB::table('cloudhouse_contract_total')->where('supplier_id', $params['supplier_id'])->select('contract_no')->get()->pluck('contract_no');
                if (!$contractNos->count()) {
                    return ['data' => [], 'totalNum' => 0];
                }
                $orderNos = DB::table('goods_transfers_detail')->whereIn('contract_no', $contractNos)->select('order_no')->get()->pluck('order_no');
                if (!$orderNos->count()) {
                    return ['data' => [], 'totalNum' => 0];
                }
                $list->whereIn('a.order_no', $orderNos);
            }

            if(!empty($params['user_id'])){
                $list = $list->where('e.user_id',$params['user_id']);
            }

            if(!empty($params['status'])){
                $list = $list->where('e.is_push',$params['status']);
            }

            if(!empty($params['box_num'])){
                $list = $list->where('e.box_num',$params['box_num']);
            }

            if(!empty($params['is_qc'])){
                $list = $list->where('e.is_qc',$params['is_qc']);
            }

            if(!empty($params['start_time'])&&!empty($params['end_time'])){
                $list = $list->whereBetween('e.createtime', [$params['start_time'], $params['end_time']]);
            }
            $data = $list
                ->leftJoin('self_spu as b','a.spu_id','=','b.id')
                ->leftJoin('self_custom_sku as c','a.custom_sku_id','=','c.id')
                ->leftJoin('self_color_size as d','c.color_id','=','d.id')
                ->leftjoin('goods_transfers as e', 'e.order_no', '=', 'a.order_no')
                ->orderBy('a.custom_sku_id','asc')
                ->orderBy('d.sort','asc')
                ->select('a.id','a.order_no', 'a.contract_no','a.custom_sku','a.group_custom_sku','a.group_custom_sku_id','a.transfers_num','a.receive_num','a.createtime','b.spu','b.old_spu','d.name','d.identifying',
                    'c.size','a.custom_sku_id','a.spu_id','a.usable_num','a.unable_num', 'e.out_house','e.in_house','e.type','e.type_detail','e.address',
                    'e.unload','e.anomaly_order','e.shop_id','e.img_url','e.file_url','e.update_cause','e.back_order_no','e.third_party_no','e.box_num','e.platform_id',
                    'e.receive_platform_id','e.total_num','e.confirm_id','e.confirm_id','e.user_id','e.receive_total_num','e.usable_total_num','e.unable_total_num','e.text',
                    'e.is_push','e.is_export','e.is_qc','e.sj_arrive_time','e.yj_arrive_time'
                )
                ->get()
                ->toArray();
            if(!empty($data)){
                $type_detail = $data[0]->type_detail;
            }else{
                return ['code' => 500, 'msg' => '没有此订单详情数据'];
            }


            //查询任务信息
            $tasks = DB::table('tasks')->where('ext', 'like', "%{$data[0]->order_no}%")->select('desc','Id','class_id','ext')->first();
            if(!empty($tasks)){
                $task_id = $tasks->Id;
            }
            //查询中转任务信息
            $box_data = DB::table('goods_transfers_box as a')->leftJoin('goods_transfers_box_detail as b','a.id','=','b.box_id')->where('a.order_no',$params['order_no'])->where('a.is_delete',0)->select('a.type','a.box_code','b.custom_sku_id','b.shelf_num','b.location_ids','b.box_num')->get();
            $shelfArr = array();
            $shelfArr2 = array();
            $boxnumArr = array();
            $box_data_arr = [];

            foreach ($box_data as $b){
                if($type_detail!=16){
                    if(isset($shelfArr[$b->custom_sku_id])){
                        $shelfArr[$b->custom_sku_id] += $b->shelf_num;
                    }else{
                        $shelfArr[$b->custom_sku_id] = $b->shelf_num;
                    }
                    $box_data_arr[$b->custom_sku_id][] = $b->box_code;
                }else{
                    if($b->type==2){
                        if(isset($shelfArr[$b->custom_sku_id])){
                            $shelfArr[$b->custom_sku_id] += $b->shelf_num;
                        }else{
                            $shelfArr[$b->custom_sku_id] = $b->shelf_num;
                        }
                    }else{
                        if(isset($shelfArr2[$b->custom_sku_id])){
                            $shelfArr2[$b->custom_sku_id] += $b->shelf_num;
                        }else{
                            $shelfArr2[$b->custom_sku_id] = $b->shelf_num;
                        }
                    }
                }
            }

            foreach ($box_data_arr as $key => $v) {
                # code...
                $v = array_unique($v);
                $codes = implode(',',$v);
                $box_data_arr[$key] = $codes;
            }

            $dbv_arr = [];
            foreach ($box_data as $bdv) {
                $dbv_arr[$bdv->custom_sku_id][] = json_decode(json_encode($bdv),true);
            }

            $is_push = $data[0]->is_push;
            $in_house = $data[0]->in_house;
            $out_house = $data[0]->out_house;


            if($data[0]->receive_platform_id){
                $receive_platform = $this->GetPlatform($data[0]->receive_platform_id);
            }

            if($data[0]->platform_id){
                $platform = $this->GetPlatform($data[0]->platform_id);
            }

            if($data[0]->user_id){
                $account = $this->GetUsers($data[0]->user_id);
            }

            if($data[0]->confirm_id){
                $confirm = $this->GetUsers($data[0]->user_id);
            }


            foreach ($data as $k=>$v){
                $data[$k]->location_name = '';
                $data[$k]->location_data = array();
                $data[$k]->img_url = json_decode($v->img_url, true);
                $data[$k]->file_url = json_decode($v->file_url, true);

                if(isset($receive_platform)){
                    $v->receive_platform = $receive_platform['name'];
                }

                if(isset($platform)){
                    $v->platform = $platform['name'];
                }

                if(isset($confirm)){
                    $v->confirm_user = $confirm['account'];
                }

                if(isset($account)){
                    $v->account = $account['account'];
                }

                $v->is_qc = $v->is_qc == 1 ? '是':'否';

                $v->group_custom_skus = [];
                $group_custom_sku = $this->GetGroupCustomSku($v->custom_sku);
                if(!$group_custom_sku){
                    $v->group_custom_sku = [];
                }else{
                    $new_group_custom_sku = [];
                    foreach ($group_custom_sku as $gv) {
                        # code...
                        $new_group_custom_sku[] = $gv['group_custom_sku'];
                    }
                    $v->group_custom_sku = $new_group_custom_sku;
                }

                $v->group_custom_skus = implode(',',$v->group_custom_sku);
                if($type_detail>5){
                    if($out_house==1||$out_house==2){
                        $data[$k]->location_type = 1;//带库位本地仓
                        $location_name = '';
                        if(isset($dbv_arr[$v->custom_sku_id])){
                            foreach ($dbv_arr[$v->custom_sku_id] as $dv) {
                                # code...
                                $ldata = $this->Getlocation($dv['location_ids']);
                                $nos = db::table('custom_sku_count')->where('location_code',$ldata['location_code'])->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
                                $no = array_column($nos,'no');
                                $no = implode(',',$no);
                                $location_name .= $ldata['location_name'].'-'.$no.' : '.$dv['box_num'].'件,';
                                $data[$k]->location_data[] = ['location_name'=> $ldata['location_name'],'location_num'=>$dv['box_num'],'location_id'=>$dv['location_ids'],'location_code'=>$ldata['location_code']];
                            }

                            $data[$k]->location_name = $location_name;
                        }else{
                            $data[$k]->location_name = '';
                            $data[$k]->location_data = [];
                        }
                    }elseif($out_house==6||$out_house==21||$out_house==23){
                        $data[$k]->location_type = 2;//不带库位本地仓
                    }
                }else{
                    if($in_house==1||$in_house==2){
                        $data[$k]->location_type = 1;//带库位本地仓
                        $location_log = DB::table('cloudhouse_location_log')->where('order_no',$params['order_no'])->where('custom_sku_id',$v->custom_sku_id)->select('location_id','num')->get();

                        if(!$location_log->isEmpty()){
                            $logArr = array();
                            foreach ($location_log as $g){
                                if(isset($logArr[$g->location_id])){
                                    $logArr[$g->location_id] += $g->num;
                                }else{
                                    $logArr[$g->location_id] = $g->num;
                                }
                            }
                            foreach ($logArr as $logK=>$logV){
                                $location_data = $this->Getlocation($logK);
                                if($location_data){
                                    $nos = db::table('custom_sku_count')->where('location_code',$location_data['location_code'])->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
                                    $no = array_column($nos,'no');
                                    $no = implode(',',$no);
                                    $data[$k]->location_name .= $location_data['location_name'].'-'.$no.' : '.$logV.'件,';
                                    $data[$k]->location_data[] = ['location_name'=>$location_data['location_name'],'location_num'=>$logV,'location_id'=>$logK,'location_code'=>$location_data['location_code']];
                                }
                            }
                        }
                    }elseif($in_house==6||$in_house==21||$in_house==23){
                        $data[$k]->location_type = 2;//不带库位本地仓
                    }
                }
                $data[$k]->location_name = rtrim($data[$k]->location_name,',');

                if($is_push!=3){
                    if(isset($shelfArr[$v->custom_sku_id])){
                        if($shelfArr[$v->custom_sku_id]>=$data[$k]->transfers_num){
                            $data[$k]->receive_num = $data[$k]->transfers_num;
                            $shelfArr[$v->custom_sku_id] = $shelfArr[$v->custom_sku_id]-$data[$k]->receive_num;
                        }else{
                            $data[$k]->receive_num = $shelfArr[$v->custom_sku_id];
                            $shelfArr[$v->custom_sku_id] = $shelfArr[$v->custom_sku_id]-$data[$k]->receive_num;
                        }
                    }
                    if(isset($shelfArr2[$v->custom_sku_id])){
                        if($shelfArr2[$v->custom_sku_id]>=$data[$k]->transfers_num){
                            $data[$k]->usable_num = $data[$k]->transfers_num;
                            $shelfArr2[$v->custom_sku_id] = $shelfArr2[$v->custom_sku_id]-$data[$k]->usable_num;
                        }else{
                            $data[$k]->usable_num = $shelfArr2[$v->custom_sku_id];
                            $shelfArr2[$v->custom_sku_id] = $shelfArr2[$v->custom_sku_id]-$data[$k]->usable_num;
                        }
                    }
                }
                $data[$k]->box_code = '';
                if(isset($box_data_arr[$v->custom_sku_id])){
                    $data[$k]->box_code = $box_data_arr[$v->custom_sku_id];
                }
                $data[$k]->img = $this->GetCustomskuImg($v->custom_sku);
            }
            $img = [];
            foreach ($data as $k => $v){
                $v->type_detail_name = Constant::GOODS_TRANSFERS_TYPE_DETAIL[$v->type_detail] ?? '';
                if (in_array($data[$k]->img, $img)){
                    $data[$k]->img = '';
                }else{
                    $img[] = $data[$k]->img;
                }
            }
            $p['title']='采购详情'.time();
            $p['title_list']  = [
                'order_no' => '订单号',
                'type_detail_name' => '出入库类型',
                'contract_no'=>'采购单号',
                'box_code'=>'中转任务号',
                'custom_sku'=>'库存sku',
                'group_custom_skus'=>'成员sku',
                'img'=>'图片',
                'spu'=>'spu',
                'name'=>'颜色',
                'identifying'=>'颜色标签',
                'size'=>'尺码',
                'transfers_num'=>'出库数量',
                'receive_num'=>'实际接受数量',
                'location_name'=>'库位',
                'text' => '备注',
                'createtime'=>'创建时间',
            ];
            if (isset($params['not_img']) && $params['not_img'] == 1){
                $p['title'] = '采购详情(无图片)'.time();
                $p['title_list']  = [
                    'custom_sku'=>'库存sku',
                    'order_no' => '包装袋码',
                    'img'=>'图片',
                    'spu'=>'spu',
                    'name'=>'颜色',
                    'size'=>'尺码',
                    'transfers_num'=>'计划出库数量',
                    'receive_num'=>'实际出货数量',
                    'createtime'=>'创建时间',
                ];
            }
            $p['data'] = $data;
            $p['data'] =  $data;
            $p['user_id'] = $params['export_user_id'];
            $p['type'] = '采购详情-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => '500', 'msg' => '加入队列失败'];
            }
            return ['type' => '200','msg' => '加入队列成功'];
        }
        return [
            'data' => $data,
            'totalNum' => $count,
        ];
    }


    
    public function save_ys_pdf($params)
    {


        $order_no = $params['order_no'];

        $task = db::table('goods_transfers')->where('order_no',$order_no)->first();

        $user_id = 0;
        if($task ){
            $user_id =$task->user_id;
        }
        $user_name = $this->GetUsers($user_id)['account'];

        $detail = db::table('goods_transfers_detail')->where('order_no',$order_no)->get();

        $ewm_url = 'http://116.62.169.253:9080/qrcode/'.$order_no.'.png';
        // var_dump( $result);
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'tcpdf' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . 'tcpdf_include.php');
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setCreator(PDF_CREATOR);
        $pdf->setAuthor('Nicola Asuni');
        $pdf->setTitle('TCPDF Example 048');
        $pdf->setSubject('TCPDF Tutorial');
        $pdf->setKeywords('TCPDF, PDF, example, test, guide');
        $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->setHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->setFooterMargin(PDF_MARGIN_FOOTER);
        $pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->AddPage();
        $pdf->setFont('stsongstdlight', '', 12);
        $pdf->setLeftMargin(3);

        // $delivery_date = $result['delivery_date'];
        // $courier_date = $result['courier_date'];
        // $shipping_date = $result['shipping_date'];
        // $air_date = $result['air_date'];
//         $tbl = "
// <table >
//     <tr>
//         <td> 压缩包号</td>
//         <td> 20240520001</td>
//     </tr>
//     <tr>
//      <td> 创建时间</td>
//      <td> 2024-05-20 16:28:14</td>
//     </tr>
//     <tr>
//      <td> 创建人</td>
//      <td> admin1</td>
//     </tr></table>";

      
//         $pdf->writeHTML($tbl, true, false, false, false, '');
//         $pdf->Write(0, '补货单明细', '', 0, 'L', true, 0, false, false, 0);
//         $pdf->setFont('stsongstdlight', '', 10);
//         $tbl2 ='
// <table>
// <tr>
// <td width="150"> SKU</td>
// <td width="40">图片</td>
// <td width="40"> 数量</td>
// ';


//         // $zuhe_data = $result['zuhe_data'];
//         $data[] = ['img'=>'https://qianyierp.oss.aliyuncs.com/image_thumbnail/ZTU5OTY3NDMxMGQ5YjNhYTFiM2JhYzc5YjUwN2ZmNmU%3D.jpg','sku'=>'SP820-black-L','num'=>100];

//         foreach ($data as $v) {     
//             $img = $v['img'];
//             $sku = $v['sku'];
//             $num = $v['num'];

//             $tbl2 .= '
// <tr>
// <td> $sku </td>
// <td> <img height="30" src="{$img}"></td>
// <td> $num</td>
// </tr>
// EOD;';
//         }
//         $tbl2 .= '</table>';

$tbl2 = '  
<div><img class="td-img" style="width:100px;height:100px;" src="'. $ewm_url.'" alt=""></div>
<table  cellspacing="0" cellpadding="1" border="1">
<tr>
    <td  colspan="2">压缩包号</td>
    <td colspan="2">'. $order_no.'</td>
</tr>
<tr>
    <td colspan="2">创建时间</td>
    <td colspan="2">'. $task->createtime.'</td>
</tr>
<tr>
    <td colspan="2">创建人</td>
    <td colspan="2">'.$user_name.'</td>
</tr>

<tr><td  colspan="4"></td></tr>

<tr>
    <td>sku</td>
    <td>中文名</td>
    <td>图片</td>
    <td>实际数量/计划数量</td>
</tr>';

foreach ($detail as $v) {
    $img = $this->GetCustomskuImg($v->custom_sku);
    $cus = $this->GetCustomSkus($v->custom_sku)['name'];
    $tbl2 .='<tr>
    <td>'.$v->custom_sku.'</td>
    <td>'.$cus.'</td>
    <td><img class="td-img" style="width:50px;height:50px;" src="'.$img.'" alt=""></td>
    <td>'.$v->receive_num.'/'.$v->transfers_num.'</td>
</tr>';
}


$tbl2 .='</table>';



    try {
        //code...
        $pdf->writeHTML($tbl2, true, false, false, false, 'left');
        db::table('goods_transfers')->where('order_no',$order_no)->update(['pdf_status'=>1]);
    } catch (\Throwable $e) {
        //throw $th;
        return['code'=>500,'msg'=>$e->getMessage().'line:'.$e->getLine()];
    }
       
        //输出PDF
        $pdf->Output(rand(1,1000).'.pdf', 'I');//I输出、D下载

    }



    public function transfers_data_detail($params){
        if(!empty($params['order_no'])){

            $list = DB::table('goods_transfers_detail as a');
            if(!empty($params['custom_sku'])){
                $list = $list->where('a.custom_sku','like','%'.$params['custom_sku'].'%');
            }
            if(!empty($params['contract_no'])){
                $list = $list->where('a.contract_no','like','%'.$params['contract_no'].'%');
            }
//            if(empty($params['type_detail'])){
//                $type_detail = $params['type_detail'];
//            }
            if (!is_array($params['order_no'])){
                $list = $list->where('a.order_no',$params['order_no']);
            }else{
                $list = $list->whereIn('a.order_no',$params['order_no']);
            }
            $data = $list
                ->leftJoin('self_spu as b','a.spu_id','=','b.id')
                ->leftJoin('self_custom_sku as c','a.custom_sku_id','=','c.id')
                ->leftJoin('self_color_size as d','c.color_id','=','d.id')
                ->leftjoin('goods_transfers as e', 'e.order_no', '=', 'a.order_no')
//                ->leftJoin('goods_transfers_box as f', 'f.order_no', '=', 'a.order_no')

                ->orderBy('a.custom_sku_id','asc')
                ->orderBy('d.sort','asc')
                ->select('a.id','a.order_no', 'a.contract_no','a.custom_sku','a.group_custom_sku','a.group_custom_sku_id',db::raw('sum(a.transfers_num) as transfers_num'),db::raw('sum(a.receive_num) as receive_num'),'a.createtime','b.spu','b.old_spu','d.name','d.identifying',
                    'c.size','a.custom_sku_id','a.spu_id','a.usable_num','a.unable_num', 'e.out_house','e.in_house','e.type','e.type_detail','e.address',
                    'e.unload','e.anomaly_order','e.shop_id','e.img_url','e.file_url','e.update_cause','e.back_order_no','e.third_party_no','e.box_num','e.platform_id',
                    'e.receive_platform_id','e.total_num','e.confirm_id','e.confirm_id','e.user_id','e.receive_total_num','e.usable_total_num','e.unable_total_num','e.text',
                    'e.is_push','e.is_export','e.is_qc','e.sj_arrive_time','e.yj_arrive_time','a.pack_num','a.save_num','e.attr'
                )
                ->groupby('a.custom_sku_id')
                ->get()
                ->toArray();
            if(!empty($data)){
                $type_detail = $data[0]->type_detail;
            }else{
                return ['code' => 500, 'msg' => '没有此订单详情数据'];
            }


            //查询任务信息
            $tasks = DB::table('tasks')->where('ext', 'like', "%{$data[0]->order_no}%")->select('desc','Id','class_id','ext')->first();
            if(!empty($tasks)){
                $task_id = $tasks->Id;
            }
            //查询中转任务信息
            $box_data = DB::table('goods_transfers_box as a')->leftJoin('goods_transfers_box_detail as b','a.id','=','b.box_id')->where('a.order_no',$params['order_no'])->where('a.is_delete',0)->select('a.type','a.box_code','b.custom_sku_id','b.shelf_num','b.location_ids','b.box_num')->get();
            $shelfArr = array();
            $shelfArr2 = array();
            $boxnumArr = array();
            $box_data_arr = [];

            foreach ($box_data as $b){
                if($type_detail!=16){
                    if(isset($shelfArr[$b->custom_sku_id])){
                        $shelfArr[$b->custom_sku_id] += $b->shelf_num;
                    }else{
                        $shelfArr[$b->custom_sku_id] = $b->shelf_num;
                    }
                    $box_data_arr[$b->custom_sku_id][] = $b->box_code;
                }else{
                    if($b->type==2){
                        if(isset($shelfArr[$b->custom_sku_id])){
                            $shelfArr[$b->custom_sku_id] += $b->shelf_num;
                        }else{
                            $shelfArr[$b->custom_sku_id] = $b->shelf_num;
                        }
                    }else{
                        if(isset($shelfArr2[$b->custom_sku_id])){
                            $shelfArr2[$b->custom_sku_id] += $b->shelf_num;
                        }else{
                            $shelfArr2[$b->custom_sku_id] = $b->shelf_num;
                        }
                    }
                }
            }

            foreach ($box_data_arr as $key => $v) {
                # code...
                $v = array_unique($v);
                $codes = implode(',',$v);
                $box_data_arr[$key] = $codes;
            }

            $dbv_arr = [];
            foreach ($box_data as $bdv) {
                $dbv_arr[$bdv->custom_sku_id][] = json_decode(json_encode($bdv),true);
            }

            $is_push = $data[0]->is_push;
            $in_house = $data[0]->in_house;
            $out_house = $data[0]->out_house;


            if($data[0]->receive_platform_id){
                $receive_platform = $this->GetPlatform($data[0]->receive_platform_id);
            }

            if($data[0]->platform_id){
                $platform = $this->GetPlatform($data[0]->platform_id);
            }

            if($data[0]->user_id){
                $account = $this->GetUsers($data[0]->user_id);
            }

            if($data[0]->confirm_id){
                $confirm = $this->GetUsers($data[0]->user_id);
            }

            $contractMdl = db::table('cloudhouse_contract_total')
                ->get(['contract_no', 'supplier_short_name'])
                ->keyBy(['contract_no']);
            foreach ($data as $k=>$v){

                $attr = json_decode($v->attr,true);
                $v->attrs =  $attr;
                $v->m_title = '';
                if(isset($attr['m_title'])){
                    $v->m_title = $attr['m_title'];
                }
    
                $v->long = '';
                if(isset($attr['long'])){
                    $v->long = $attr['long'];
                }
    
                $v->width = '';
                if(isset($attr['width'])){
                    $v->width = $attr['width'];
                }
    
                $v->height = '';
                if(isset($attr['height'])){
                    $v->height = $attr['height'];
                }
    
                $v->weight = '';
                if(isset($attr['weight'])){
                    $v->weight = $attr['weight'];
                }

                $v->desc = '';
                if(isset($attr['desc'])){
                    $v->desc = $attr['desc'];
                }
                
    
                $v->photo = [];
                if(isset($attr['photo'])){
                    $v->photo = json_decode($attr['photo'],true);
                }
    
                $data[$k]->location_name = '';
                $data[$k]->location_data = array();
                $data[$k]->img_url = json_decode($v->img_url, true);
                $data[$k]->file_url = json_decode($v->file_url, true);

                $data[$k]->supplier_name = $contractMdl[$data[$k]->contract_no]->supplier_short_name ?? '';

                $data[$k]->receive_num = (int)$v->receive_num;
                $data[$k]->transfers_num = (int)$v->transfers_num;

                if(isset($receive_platform)){
                    $v->receive_platform = $receive_platform['name'];
                }

                if(isset($platform)){
                    $v->platform = $platform['name'];
                }

                if(isset($confirm)){
                    $v->confirm_user = $confirm['account'];
                }

                if(isset($account)){
                    $v->account = $account['account'];
                }

                $v->is_qc = $v->is_qc == 1 ? '是':'否';

                $v->group_custom_skus = [];
                $group_custom_sku = $this->GetGroupCustomSku($v->custom_sku);
                if(!$group_custom_sku){
                    $v->group_custom_sku = [];
                }else{
                    $new_group_custom_sku = [];
                    foreach ($group_custom_sku as $gv) {
                        # code...
                        $new_group_custom_sku[] = $gv['group_custom_sku'];
                    }
                    $v->group_custom_sku = $new_group_custom_sku;
                }

                $v->group_custom_skus = implode(',',$v->group_custom_sku);
                if($type_detail>5){
                    if($out_house==1||$out_house==2){
                        $data[$k]->location_type = 1;//带库位本地仓
                        $location_name = '';
                        if(isset($dbv_arr[$v->custom_sku_id])){
                            foreach ($dbv_arr[$v->custom_sku_id] as $dv) {
                                # code...
                                $ldata = $this->Getlocation($dv['location_ids']);
                                $nos = db::table('custom_sku_count')->where('location_code',$ldata['location_code'])->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
                                $no = array_column($nos,'no');
                                $no = implode(',',$no);
                                $location_name .= $ldata['location_name'].'-'.$no.' : '.$dv['box_num'].'件,';
                                $data[$k]->location_data[] = ['location_name'=> $ldata['location_name'],'location_num'=>$dv['box_num'],'location_id'=>$dv['location_ids'],'location_code'=>$ldata['location_code']];
                            }

                            $data[$k]->location_name = $location_name;
                        }else{
                            $data[$k]->location_name = '';
                            $data[$k]->location_data = [];
                        }
                    }elseif($out_house==6||$out_house==21||$out_house==23){
                        $data[$k]->location_type = 2;//不带库位本地仓
                    }
                }else{
                    if($in_house==1||$in_house==2){
                        $data[$k]->location_type = 1;//带库位本地仓
                        $location_log = DB::table('cloudhouse_location_log')->where('order_no',$params['order_no'])->where('custom_sku_id',$v->custom_sku_id)->select('location_id','num')->get();

                        if(!$location_log->isEmpty()){
                            $logArr = array();
                            foreach ($location_log as $g){
                                if(isset($logArr[$g->location_id])){
                                    $logArr[$g->location_id] += $g->num;
                                }else{
                                    $logArr[$g->location_id] = $g->num;
                                }
                            }
                            foreach ($logArr as $logK=>$logV){
                                $location_data = $this->Getlocation($logK);
                                if($location_data){
                                    $nos = db::table('custom_sku_count')->where('location_code',$location_data['location_code'])->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
                                    $no = array_column($nos,'no');
                                    $no = implode(',',$no);
                                    $data[$k]->location_name .= $location_data['location_name'].'-'.$no.' : '.$logV.'件,';
                                    $data[$k]->location_data[] = ['location_name'=>$location_data['location_name'],'location_num'=>$logV,'location_id'=>$logK,'location_code'=>$location_data['location_code']];
                                }
                            }
                        }
                    }elseif($in_house==6||$in_house==21||$in_house==23){
                        $data[$k]->location_type = 2;//不带库位本地仓
                    }
                }
                $data[$k]->location_name = rtrim($data[$k]->location_name,',');

                if($is_push!=3){
                    if(isset($shelfArr[$v->custom_sku_id])){
                        if($shelfArr[$v->custom_sku_id]>=$data[$k]->transfers_num){
                            $data[$k]->receive_num = $data[$k]->transfers_num;
                            $shelfArr[$v->custom_sku_id] = $shelfArr[$v->custom_sku_id]-$data[$k]->receive_num;
                        }else{
                            $data[$k]->receive_num = $shelfArr[$v->custom_sku_id];
                            $shelfArr[$v->custom_sku_id] = $shelfArr[$v->custom_sku_id]-$data[$k]->receive_num;
                        }
                    }
                    if(isset($shelfArr2[$v->custom_sku_id])){
                        if($shelfArr2[$v->custom_sku_id]>=$data[$k]->transfers_num){
                            $data[$k]->usable_num = $data[$k]->transfers_num;
                            $shelfArr2[$v->custom_sku_id] = $shelfArr2[$v->custom_sku_id]-$data[$k]->usable_num;
                        }else{
                            $data[$k]->usable_num = $shelfArr2[$v->custom_sku_id];
                            $shelfArr2[$v->custom_sku_id] = $shelfArr2[$v->custom_sku_id]-$data[$k]->usable_num;
                        }
                    }
                }
                $data[$k]->box_code = '';
                if(isset($box_data_arr[$v->custom_sku_id])){
                    $data[$k]->box_code = $box_data_arr[$v->custom_sku_id];
                }
                $data[$k]->img = $this->GetCustomskuImg($v->custom_sku);

                $group = db::table('self_group_custom_sku')->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
                $data[$k]->group = '';
                if($group){
                    $data[$k]->group = implode(',',array_column($group,'group_custom_sku'));
                }
                $data[$k]->ratio_detail = [];
                $data[$k]->receive_detail = [];

                $ratio= db::table('goods_transfers_detail')->where('custom_sku_id',$v->custom_sku_id)->where('order_no',$v->order_no)->first();
                $ratios = [];
                if($ratio){
                    $ratio_detail =  json_decode($ratio->ratio_detail,true);
                    if(is_array($ratio_detail)){
                        foreach ($ratio_detail as $rp => $rv) {
                            # code...
                            $r_one['platform'] = db::table('platform')->where('Id',$rp)->first()->name;
                            $r_one['platform_id'] = $rp;
                            $r_one['num'] =$rv;
                            $ratios[] = $r_one;
                        }
                        $data[$k]->ratio_detail =  $ratios;
                 
                    }

                    $goods_transfers_platform_log = db::table('goods_transfers_platform_log')->where('order_no',$v->order_no)->where('custom_sku_id',$v->custom_sku_id)->get();

                    $gplv_arr = [];
                    foreach ($goods_transfers_platform_log as $gplv) {
                        # code...
                        if(isset( $gplv_arr[$gplv->platform_id])){
                            $gplv_arr[$gplv->platform_id] +=$gplv->receive_num;
                        }else{
                            $gplv_arr[$gplv->platform_id] = $gplv->receive_num;
                        }
                        
                    }
                    $receives = [];
                    foreach ($gplv_arr as $gplv_pid => $gplv_v) {
                        # code...
                        $rn_one['platform'] = db::table('platform')->where('Id',$gplv_pid)->first()->name;
                        $rn_one['platform_id'] = $gplv_pid;
                        $rn_one['num'] =$gplv_v;
                        $receives[] = $rn_one;
                    }

                    $data[$k]->receive_detail = $receives;
                    // $receive_num_arr =  json_decode($ratio->receive_num_arr,true);
                    // if(is_array($receive_num_arr)){
                    //     foreach ($receive_num_arr as $rnp => $rnv) {
                    //         # code...
                    //         $rn_one['platform'] = db::table('platform')->where('Id',$rnp)->first()->name;
                    //         $rn_one['platform_id'] = $rnp;
                    //         $rn_one['num'] =$rnv;
                    //         $receives[] = $rn_one;
                    //     }
                    //     $data[$k]->receive_detail = $receives;
                    // }

                    // $a['platform'] = '马来西亚';
                    // $a['platform_id'] = 1;
                    // $a['num'] = 100;
                    // $aa['platform'] = '菲律宾';
                    // $aa['platform_id'] = 2;
                    // $aa['num'] = 200;

                    $v->out_inventory_num = [];
                    $v->plan_out_inventory_num = [];
                    $out_inventory = db::table('goods_transfers as a')->leftjoin('goods_transfers_detail as b','a.order_no','=','b.order_no')->where('a.out_no',$v->order_no)->where('b.custom_sku_id',$v->custom_sku_id)->groupby('a.platform_id')->select('a.platform_id',db::raw('sum(b.transfers_num) as total_num'),db::raw('sum(b.receive_num) as receive_total_num'))->get();


                    $out_inventory = db::table('goods_transfers_platform_log')->where('out_no',$v->order_no)->where('custom_sku_id',$v->custom_sku_id)->groupby('platform_id')->select('platform_id',db::raw('sum(transfers_num) as total_num'),db::raw('sum(receive_num) as receive_total_num'))->get();

                    foreach ($out_inventory as $oiv) {
                        # code...
                        $one['platform']= db::table('platform')->where('Id',$oiv->platform_id)->first()->name;
                        $one['platform_id']=$oiv->platform_id;
                        if($oiv->total_num>0){
                            $one['num'] = $oiv->total_num;
                            $v->plan_out_inventory_num[] = $one;
                        }
                        if($oiv->receive_total_num>0){
                            $one['num'] = $oiv->receive_total_num;
                            $v->out_inventory_num[] = $one;
                        }

                    }


                    // $v->plan_out_inventory_num[] = $a;
                    // $v->plan_out_inventory_num[] = $aa;

                    // $v->out_inventory_num[] = $a;
                    // $v->out_inventory_num[] = $aa;
                }

              

            }
            $posttype = $params['posttype']??1;
            if($posttype==2){
                $img = [];
                foreach ($data as $k => $v){
                    if (in_array($data[$k]->img, $img)){
                        $data[$k]->img = '';
                    }else{
                        $img[] = $data[$k]->img;
                    }
                }
                $p['title']='采购详情'.time();
                $p['title_list']  = [
                    'custom_sku'=>'库存sku',
                    'order_no' => '包装袋码',
                    'img'=>'图片',
                    'spu'=>'spu',
                    'name'=>'颜色',
                    'size'=>'尺码',
                    'transfers_num'=>'计划出库数量',
                    'receive_num'=>'实际出货数量',
                    'createtime'=>'创建时间',
                ];
                $p['data'] = $data;
//                $this->excel_expord($p);

                $p['data'] =  $data;
                $p['user_id'] = $params['find_user_id'];
                $p['type'] = '采购详情-导出';
//                return $this->publicExport($p);
                $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
                try {
                    $job::runJob($p);
                } catch(\Exception $e){
                    return ['type' => '500', 'msg' => '加入队列失败'];
                }
                return ['type' => '200','msg' => '加入队列成功'];

            }
            return ['code'=>200,'msg'=>['data'=>$data,'task_id'=>isset($task_id)?$task_id:'']];
        }else{
            return ['code'=>500,'msg'=>'没有入库单id'];
        }
    }

    public function goods_detail_list($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $list = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->where('type_detail',2)->where('is_push',3);

        if(isset($params['order_no'])){
            $list = $list->where('a.order_no',$params['order_no']);
        }

        if(isset($params['custom_sku'])){
            $cus_id = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
            $cus_ids = array_column($cus_id,'id');

            $list = $list->whereIn('a.custom_sku_id',$cus_ids);
        }

        $totalNum = $list->get()->count();
        $list = $list->offset($page)->limit($limit)->orderby('a.id', 'desc')->select('a.order_no','a.custom_sku','a.spu','a.transfers_num','a.receive_num','a.ratio_detail','a.custom_sku_id','a.createtime')->get();

        foreach ($list as $v) {
            # code...
            $cus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            $v->img = $this->GetCustomskuImg($v->custom_sku);
            $v->color = $cus->color_name.'/'.$cus->color;
            $v->size = $cus->size;
            $v->spu = $cus->spu;
            $v->out_inventory_num = [];
            $v->plan_out_inventory_num = [];
            $out_inventory = db::table('goods_transfers as a')->leftjoin('goods_transfers_detail as b','a.order_no','=','b.order_no')->where('a.out_no',$v->order_no)->where('b.custom_sku_id',$v->custom_sku_id)->groupby('a.platform_id')->select('a.platform_id',db::raw('sum(b.transfers_num) as total_num'),db::raw('sum(b.receive_num) as receive_total_num'))->get();


            $out_inventory = db::table('goods_transfers_platform_log')->where('out_no',$v->order_no)->where('custom_sku_id',$v->custom_sku_id)->groupby('platform_id')->select('platform_id',db::raw('sum(transfers_num) as total_num'),db::raw('sum(receive_num) as receive_total_num'))->get();

            foreach ($out_inventory as $oiv) {
                # code...
                $one['platform']= db::table('platform')->where('Id',$oiv->platform_id)->first()->name;
                $one['platform_id']=$oiv->platform_id;
                if($oiv->total_num>0){
                    $one['num'] = $oiv->total_num;
                    $v->plan_out_inventory_num[] = $one;
                }
                if($oiv->receive_total_num>0){
                    $one['num'] = $oiv->receive_total_num;
                    $v->out_inventory_num[] = $one;
                }

                

            }


            try {
                //code...
                $ratio_detail =  json_decode($v->ratio_detail,true);
                if(is_array($ratio_detail)){
                    $ratios = [];
                    foreach ($ratio_detail as $rp => $rv) {
                        # code...
                        $r_one['platform'] = db::table('platform')->where('Id',$rp)->first()->name;
                        $r_one['platform_id'] = $rp;
                        $r_one['num'] =$rv;
                        $ratios[] = $r_one;
                    }
                    $v->ratio_detail =  $ratios;
                }
            } catch (\Throwable $th) {
                //throw $th;
                $v->ratio_detail = [];

            }
       


        }
        return['code'=>200,'msg'=>'获取成功','data'=>['count'=>$totalNum,'data'=>$list]];
    }

    public function goods_cloud_new($params){

        $push_time = date('Y-m-d H:i:s',time());
        if(!empty($params['order_no'])) {

            $isBox = DB::table('goods_transfers_box')->where('order_no',$params['order_no'])->select('id')->first();
            if(!empty($isBox)){
                DB::table('goods_transfers_box')->where('id',$isBox->id)->delete();
                DB::table('goods_transfers_box_detail')->where('box_id',$isBox->id)->delete();
            }

            $list = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b', 'a.order_no', '=', 'b.order_no')
                ->where('a.order_no', $params['order_no'])
                ->select('b.custom_sku', 'b.transfers_num', 'b.order_no', 'a.type_detail', 'a.out_house', 'b.custom_sku_id', 'a.in_house', 'a.anomaly_order',
                    'b.spu', 'b.spu_id','b.contract_no','a.text','a.shop_id','a.user_id','a.unload','a.yj_arrive_time','a.back_order_no','a.platform_id','a.receive_platform_id')
                ->get()
                ->toArray();

            if (!empty($list)) {
                $detail = [];
                $custom_sku_arr = [];
                $platfrom_id = 0;
                if($list[0]->platform_id){
                    $platfrom_id = $list[0]->platform_id;
                }elseif($list[0]->shop_id){
                    $shopData = $this->GetShop($list[0]->shop_id);
                    if($shopData){
                        $platfrom_id = $shopData['platform_id'];
                    }
                }
                foreach ($list as $v) {

                    // if($type_detail==2){
                    //     //采购入库   按比例分配  生成平台推荐数量
            
                    // }



                    if(isset($detail[$v->custom_sku_id])){
                        $detail[$v->custom_sku_id] = ['custom_sku' => $v->custom_sku, 'num' => $detail[$v->custom_sku_id]['num']+$v->transfers_num,
                            'custom_sku_id' => $v->custom_sku_id, 'spu_id' => $v->spu_id, 'spu' => $v->spu,'contract_no'=> $v->contract_no];
                    }else{
                        $detail[$v->custom_sku_id] = ['custom_sku' => $v->custom_sku, 'num' => $v->transfers_num,
                            'custom_sku_id' => $v->custom_sku_id, 'spu_id' => $v->spu_id, 'spu' => $v->spu,'contract_no'=> $v->contract_no];
                    }
                    $custom_sku_arr[] = $v->custom_sku_id;
                }
            } else {
                return ['code' => 500, 'msg' => '此入库单没有入库数据'];
            }
            

            $in_house = $list[0]->in_house;
            $out_house = $list[0]->out_house;
            $type_detail = $list[0]->type_detail;
            $back_order_no = $list[0]->back_order_no;
            $anomaly_order = $list[0]->anomaly_order;
            $merchandiser = $this->GetUsers($list[0]->user_id)['account']??'';
            if($list[0]->unload==1){
                $unload = '仓库';
            }else{
                $unload = '工厂';
            }
            $yj_arrive_time = $list[0]->yj_arrive_time;
            $quequeres['order_no'] = $list[0]->order_no;
            $quequeres['detail'] = $detail;
//            $params['out_house'] = $list[0]->out_house;
            db::beginTransaction();    //开启事务



            $tasks_class = DB::table('task_class')->where('warehouse_id',$out_house)->where('type_detail',$type_detail)->first();
            $time = date('Y-m-d H:i:s');
            if($type_detail==1){
                DB::table('goods_transfers')->where('order_no', $back_order_no)->update(['back_order_no' => $params['order_no']]);
            }else{
                if(empty($tasks_class)) {
                    DB::table('goods_transfers')->where('order_no', $params['order_no'])->update(['is_push' => 2,'push_time'=>$push_time]);
                }
            }
            // if($out_house==1||$out_house==2||$out_house == 3||$out_house==6||$out_house==21||$out_house==23){

            //     $box_id = $this->Addbox($params['order_no'],$out_house);
            //     if($box_id){
            //         $anomaly_type = 1;
            //         if($anomaly_order=='次品出库'){
            //             $anomaly_type = 2;
            //         }
            //         foreach ($detail as $d){
            //             if($type_detail!=1){
            //                 $res = $this->PointsLocation($d['custom_sku_id'],$out_house,$d['num'],$box_id,$d['custom_sku'],$platfrom_id,$type_detail,$anomaly_type);
            //                 if($res==1){
            //                     if(empty($tasks_class)){
            //                         DB::table('goods_transfers')->where('order_no', $params['order_no'])->update(['is_push' => 2,'push_time'=>$push_time]);
            //                     }
            //                 }else{
            //                     db::rollback();// 回调
            //                     return ['code' => 500, 'msg' => $res];
            //                 }
            //             }else{
            //                 if(empty($tasks_class)){
            //                     DB::table('goods_transfers')->where('order_no', $params['order_no'])->update(['is_push' => 2,'push_time'=>$push_time]);
            //                 }
            //             }
            //         }
            //     }else{
            //         db::rollback();// 回调
            //         return ['code' => 500, 'msg' => '新增出库任务箱失败'];
            //     }
                
            // }
            
   

            
            db::commit();
            return ['code' => 200, 'msg' => '推送成功'];
            // if(isset($box_id)){
            //     $ext = '';
            //     $class_id = '';

            //     if(!empty($tasks_class)){
            //         $class_id = $tasks_class->id;
            //         $task_class_module = DB::table('task_class_module')->where('class_id',$class_id)->select('name')->get()->toArray();
            //         if(!empty($task_class_module)){
            //             $ext = array_column($task_class_module,'name');
            //         }
            //     }
            //     return ['code' => 200, 'msg' => '推送成功','box_id'=>$box_id,
            //         'data'=>[
            //             'class_id'=>$class_id,'transfers_id'=>$params['order_no'],'transfers_link'=>'/transfer_request_details?order_no='
            //                 .$params['order_no'],'ext'=>$ext
            //         ]
            //     ];
            // }else{
            //     return ['code' => 200, 'msg' => '推送成功'];
            // }

        } else{
            return ['code'=>500,'msg'=>'没有入库单id'];
        }
    }

    public function goods_cloud($params){

//        $token = $params['token'];
//        $user = DB::table('users')->where('token',$token)->select('Id')->first();
//        if($user->Id==276){
//            $status=1;
//        }else{
//            $status = 0;
//        }
        $is_re_push =  DB::table('goods_transfers')->where('is_push',2)->whereIn('is_push',[2,4])->where('type_detail',2)->first();

        if($is_re_push){
            return ['code' => 500, 'msg' => '已有推送,或操作中订单，请先完结该订单'.$is_re_push->order_no];
        }
        $push_time = date('Y-m-d H:i:s',time());
        if(!empty($params['order_no'])) {

            $isBox = DB::table('goods_transfers_box')->where('order_no',$params['order_no'])->select('id')->first();
            if(!empty($isBox)){
                DB::table('goods_transfers_box')->where('id',$isBox->id)->delete();
                DB::table('goods_transfers_box_detail')->where('box_id',$isBox->id)->delete();
            }

            $list = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b', 'a.order_no', '=', 'b.order_no')
                ->where('a.order_no', $params['order_no'])
                ->select('b.custom_sku', 'b.transfers_num', 'b.order_no', 'a.type_detail', 'a.out_house', 'b.custom_sku_id', 'a.in_house', 'a.anomaly_order',
                    'b.spu', 'b.spu_id','b.contract_no','a.text','a.shop_id','a.user_id','a.unload','a.yj_arrive_time','a.back_order_no','a.platform_id','a.receive_platform_id')
                ->get()
                ->toArray();

            if (!empty($list)) {
                $detail = [];
                $custom_sku_arr = [];
                $platfrom_id = 0;
                if($list[0]->platform_id){
                    $platfrom_id = $list[0]->platform_id;
                }elseif($list[0]->shop_id){
                    $shopData = $this->GetShop($list[0]->shop_id);
                    if($shopData){
                        $platfrom_id = $shopData['platform_id'];
                    }
                }
                foreach ($list as $v) {
                    if(isset($detail[$v->custom_sku_id])){
                        $detail[$v->custom_sku_id] = ['custom_sku' => $v->custom_sku, 'num' => $detail[$v->custom_sku_id]['num']+$v->transfers_num,
                            'custom_sku_id' => $v->custom_sku_id, 'spu_id' => $v->spu_id, 'spu' => $v->spu,'contract_no'=> $v->contract_no];
                    }else{
                        $detail[$v->custom_sku_id] = ['custom_sku' => $v->custom_sku, 'num' => $v->transfers_num,
                            'custom_sku_id' => $v->custom_sku_id, 'spu_id' => $v->spu_id, 'spu' => $v->spu,'contract_no'=> $v->contract_no];
                    }
                    $custom_sku_arr[] = $v->custom_sku_id;
                }
            } else {
                return ['code' => 500, 'msg' => '此入库单没有入库数据'];
            }
            

            $in_house = $list[0]->in_house;
            $out_house = $list[0]->out_house;
            $type_detail = $list[0]->type_detail;
            $back_order_no = $list[0]->back_order_no;
            $anomaly_order = $list[0]->anomaly_order;
            $merchandiser = $this->GetUsers($list[0]->user_id)['account']??'';
            if($list[0]->unload==1){
                $unload = '仓库';
            }else{
                $unload = '工厂';
            }
            $yj_arrive_time = $list[0]->yj_arrive_time;
            $quequeres['order_no'] = $list[0]->order_no;
            $quequeres['detail'] = $detail;
//            $params['out_house'] = $list[0]->out_house;
            db::beginTransaction();    //开启事务

            if ($in_house == 3) {

                $quequeres['type'] = 'DBRK';
                $quequeres['text'] = $list[0]->text;
                //云仓则加入队列
                $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                try {
                    $cloud::inhouseJob($quequeres);
                } catch (\Exception $e) {
                    Redis::Lpush('in_house_fail', json_encode($quequeres));
                }
            } elseif ($in_house == 1 || $in_house == 2 || $in_house == 6 || $in_house == 21||$in_house==23) {

                $tasks_class = DB::table('task_class')->where('warehouse_id',$out_house)->where('type_detail',$type_detail)->first();
                $time = date('Y-m-d H:i:s');
                if($type_detail==1){
                    DB::table('goods_transfers')->where('order_no', $back_order_no)->update(['back_order_no' => $params['order_no']]);
                }else{
                    if(empty($tasks_class)) {
                        DB::table('goods_transfers')->where('order_no', $params['order_no'])->update(['is_push' => 2,'push_time'=>$push_time]);
                    }
                }
                // if($out_house==1||$out_house==2||$out_house == 3||$out_house==6||$out_house==21||$out_house==23){

                //     $box_id = $this->Addbox($params['order_no'],$out_house);
                //     if($box_id){
                //         $anomaly_type = 1;
                //         if($anomaly_order=='次品出库'){
                //             $anomaly_type = 2;
                //         }
                //         foreach ($detail as $d){
                //             if($type_detail!=1){
                //                 $res = $this->PointsLocation($d['custom_sku_id'],$out_house,$d['num'],$box_id,$d['custom_sku'],$platfrom_id,$type_detail,$anomaly_type);
                //                 if($res==1){
                //                     if(empty($tasks_class)){
                //                         DB::table('goods_transfers')->where('order_no', $params['order_no'])->update(['is_push' => 2,'push_time'=>$push_time]);
                //                     }
                //                 }else{
                //                     db::rollback();// 回调
                //                     return ['code' => 500, 'msg' => $res];
                //                 }
                //             }else{
                //                 if(empty($tasks_class)){
                //                     DB::table('goods_transfers')->where('order_no', $params['order_no'])->update(['is_push' => 2,'push_time'=>$push_time]);
                //                 }
                //             }
                //         }
                //     }else{
                //         db::rollback();// 回调
                //         return ['code' => 500, 'msg' => '新增出库任务箱失败'];
                //     }
                //     if($out_house==3){

                //         if ($type_detail > 6 && $type_detail < 13) {
                //             $quequeres['type'] = 'PTCK';
                //             $quequeres['text'] = $list[0]->text;

                //             //云仓则加入队列
                //             $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                //             try {
                //                 $cloud::outhouseJob($quequeres);
                //                 return ['code' => 200, 'msg' => '推送成功！'];
                //             } catch (\Exception $e) {
                //                 db::rollback();// 回调
                //                 Redis::Lpush('out_house_fail', json_encode($quequeres['order_no']));
                //                 return ['code' => 500, 'msg' => '推送失败'];
                //             }
                //         }
                //     }
                // }
            } else {
                $time = date('Y-m-d H:i:s');
                if($out_house==1||$out_house==2||$out_house == 3||$out_house==6||$out_house==21||$out_house==23){

                    $tasks_class = DB::table('task_class')->where('warehouse_id',$out_house)->where('type_detail',$type_detail)->first();
                    $box_id = $this->Addbox($params['order_no'],$out_house);
                    if($box_id){
                        $anomaly_type = 1;
                        if($anomaly_order=='次品出库'){
                            $anomaly_type = 2;
                        }
                        foreach ($detail as $d){
                            $res = $this->PointsLocation($d['custom_sku_id'],$out_house,$d['num'],$box_id,$d['custom_sku'],$platfrom_id,$type_detail, $anomaly_type);
                            if($res==1){
                                if(empty($tasks_class)){
                                    DB::table('goods_transfers')->where('order_no', $params['order_no'])->update(['is_push' => 2,'push_time'=>$push_time]);
                                }
                            }else{
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => $res];
                            }
                        }
                    }else{
                        db::rollback();// 回调
                        return ['code' => 500, 'msg' => '新增出库任务箱失败'];
                    }
                    if ($out_house == 3) {
                        if ($type_detail > 6 && $type_detail < 13) {
                            $quequeres['type'] = 'PTCK';
                            $quequeres['text'] = $list[0]->text;
                            //云仓则加入队列
                            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                            try {
                                $cloud::outhouseJob($quequeres);
                                return ['code' => 200, 'msg' => '推送成功！'];
                            } catch (\Exception $e) {
                                db::rollback();// 回调
                                Redis::Lpush('out_house_fail', json_encode($quequeres['order_no']));
                                return ['code' => 500, 'msg' => '推送失败'];
                            }
                        }
                    }
                    if($type_detail==16){
                        $box_id2 = $this->Addbox2($params['order_no'],$out_house);
                        if(!$box_id2){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'生成上架任务失败'];
                        }
                    }
                }
            }

            if($in_house!=3&&$out_house!=3){
                if($type_detail > 6 && $type_detail < 13){
                    if($out_house==1){
                        $house_name = '同安仓';
                        $house_user = [309,313];
                    }elseif($out_house==2){
                        $house_name = '泉州仓';
                        $house_user = [409];
                    }elseif($out_house==6){
                        $house_name = '工厂寄存仓';

                    }elseif($out_house==21){
                        $house_name = '工厂直发仓';

                    }
                    $content1 = '通知：'.$house_name.'有新的出库任务'.'，请在 出库管理-'.self::TYPE_DETAIL[$type_detail].' 菜单查看，出库单号：'.$params['order_no'];
                }elseif($type_detail<6){
                    if($in_house==1){
                        $house_name = '同安仓';
                        $house_user = [309,313];
                    }elseif($in_house==2){
                        $house_name = '泉州仓';
                        $house_user = [409];
                    }elseif($in_house==6){
                        $house_name = '工厂寄存仓';

                    }elseif($in_house==21){
                        $house_name = '工厂直发仓';

                    }
                    if($type_detail==2){
                        $content1 = '通知：工厂有货即将到'.$house_name.'，请根据单号在 入库管理-采购入库查看明细，入库单号：'.$params['order_no'].'，跟单员：'.$merchandiser.'卸货方：'.$unload.'，预计到达时间：'.$yj_arrive_time;
                    }else{
                        $content1 = '通知：'.$house_name.'有新的入库任务'.'，请在 入库管理-'.self::TYPE_DETAIL[$type_detail].' 菜单查看，入库单号：'.$params['order_no'];
                    }
                }
            }
            // if(isset($house_user)){
            //     $res = $this->warehouseSend($content1,$house_user);
            // }
            db::commit();
            if(isset($box_id)){
                $ext = '';
                $class_id = '';

                if(!empty($tasks_class)){
                    $class_id = $tasks_class->id;
                    $task_class_module = DB::table('task_class_module')->where('class_id',$class_id)->select('name')->get()->toArray();
                    if(!empty($task_class_module)){
                       $ext = array_column($task_class_module,'name');
                    }
                }
                return ['code' => 200, 'msg' => '推送成功','box_id'=>$box_id,
                    'data'=>[
                        'class_id'=>$class_id,'transfers_id'=>$params['order_no'],'transfers_link'=>'/transfer_request_details?order_no='
                            .$params['order_no'],'ext'=>$ext
                    ]
                ];
            }else{
                return ['code' => 200, 'msg' => '推送成功'];
            }

        } else{
            return ['code'=>500,'msg'=>'没有入库单id'];
        }
    }

    public function transfers_data_detail_get($params){
        if(!empty($params['order_no'])){

            $list = DB::table('goods_transfers_detail as a');
            if(!empty($params['custom_sku'])){
                $list = $list->where('a.custom_sku','like','%'.$params['custom_sku'].'%');
            }
            if(!empty($params['contract_no'])){
                $list = $list->where('a.contract_no','like','%'.$params['contract_no'].'%');
            }
            if(empty($params['type_detail'])){
                return ['code'=>500,'msg'=>'未获取到清单类型'];
            }else{
                $type_detail = $params['type_detail'];
            }

            $data = $list
                ->leftJoin('self_spu as b','a.spu_id','=','b.id')
                ->leftJoin('self_custom_sku as c','a.custom_sku_id','=','c.id')
                ->leftJoin('self_color_size as d','c.color_id','=','d.id')
                ->leftjoin('goods_transfers as e', 'e.order_no', '=', 'a.order_no')
                ->leftJoin('goods_transfers_box as f', 'f.order_no', '=', 'a.order_no')
                ->where('a.order_no',$params['order_no'])
                ->orderBy('a.custom_sku_id','asc')
                ->orderBy('d.sort','asc')
                ->select('a.order_no', 'a.contract_no','a.custom_sku','a.transfers_num','a.receive_num','a.createtime','b.spu','b.old_spu','d.name','d.identifying','c.size','a.custom_sku_id','a.spu_id', 'e.text', 'f.id as box_id', 'f.box_code')
                ->get()
                ->toArray();
            $box_data = DB::table('goods_transfers_box as a')->leftJoin('goods_transfers_box_detail as b','a.id','=','b.box_id')->where('a.order_no',$params['order_no'])->where('a.is_delete',0)->select('a.box_code','b.custom_sku_id','b.shelf_num','b.location_ids','b.box_num')->get();
            $shelfArr = array();
            $boxnumArr = array();
            $box_data_arr = [];
            foreach ($box_data as $b){
                if(isset($shelfArr[$b->custom_sku_id])){
                    $shelfArr[$b->custom_sku_id] += $b->shelf_num;
                }else{
                    $shelfArr[$b->custom_sku_id] = $b->shelf_num;
                }

                // if(isset($box_data_arr[$b->custom_sku_id])){
                //     $box_data_arr[$b->custom_sku_id] .= $b->box_code;
                // }else{
                //     $box_data_arr[$b->custom_sku_id] = $b->box_code;
                // }
                $box_data_arr[$b->custom_sku_id][] = $b->box_code;
            }

            foreach ($box_data_arr as $key => $v) {
                # code...
                $v = array_unique($v);
                $codes = implode(',',$v);
                $box_data_arr[$key] = $codes;
            }

            $dbv_arr = [];
            foreach ($box_data as $bdv) {
                $dbv_arr[$bdv->custom_sku_id][] = json_decode(json_encode($bdv),true);
            }



            foreach ($data as $k=>$v){
                $data[$k]->location_name = '';
                $data[$k]->location_data = array();
                if($type_detail>5){
                    $location_name = '';
                    if(isset($dbv_arr[$v->custom_sku_id])){
                        foreach ($dbv_arr[$v->custom_sku_id] as $dv) {
                            # code...
                            $ldata = $this->Getlocation($dv['location_ids']);
                            $nos = db::table('custom_sku_count')->where('location_code',$ldata['location_code'])->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
                            $no = array_column($nos,'no');
                            $no = implode(',',$no);
                            $location_name .= $ldata['location_name'].'-'.$no.' : '.$dv['box_num'].'件,';
                            $data[$k]->location_data[] = ['location_name'=> $ldata['location_name'],'location_num'=>$dv['box_num'],'location_id'=>$dv['location_ids'],'location_code'=>$ldata['location_code']];
                        }

                        $data[$k]->location_name = $location_name;
                    }else{
                        $data[$k]->location_name = '';
                        $data[$k]->location_data = [];
                    }

                }else{
                    $location_log = DB::table('cloudhouse_location_log')->where('order_no',$params['order_no'])->where('custom_sku_id',$v->custom_sku_id)->select('location_id','num')->get();

                    if(!$location_log->isEmpty()){
                        $logArr = array();
                        foreach ($location_log as $g){
                            if(isset($logArr[$g->location_id])){
                                $logArr[$g->location_id] += $g->num;
                            }else{
                                $logArr[$g->location_id] = $g->num;
                            }
                        }
                        foreach ($logArr as $logK=>$logV){
                            $location_data = $this->Getlocation($logK);
                            if($location_data){
                                $nos = db::table('custom_sku_count')->where('location_code',$location_data['location_code'])->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
                                $no = array_column($nos,'no');
                                $no = implode(',',$no);
                                $data[$k]->location_name .= $location_data['location_name'].'-'.$no.' : '.$logV.'件,';
                                $data[$k]->location_data[] = ['location_name'=>$location_data['location_name'],'location_num'=>$logV,'location_id'=>$logK,'location_code'=>$location_data['location_code']];
                            }
                        }
                    }
                }
                $data[$k]->location_name = rtrim($data[$k]->location_name,',');


                if(isset($shelfArr[$v->custom_sku_id])){
                    if($shelfArr[$v->custom_sku_id]>=$data[$k]->transfers_num){
                        $data[$k]->receive_num = $data[$k]->transfers_num;
                        $shelfArr[$v->custom_sku_id] = $shelfArr[$v->custom_sku_id]-$data[$k]->receive_num;
                    }else{
                        $data[$k]->receive_num = $shelfArr[$v->custom_sku_id];
                    }
                }

                $data[$k]->box_code = '';
                if(isset($box_data_arr[$v->custom_sku_id])){
                    $data[$k]->box_code = $box_data_arr[$v->custom_sku_id];
                }
                $data[$k]->img = $this->GetCustomskuImg($v->custom_sku);
            }

            $posttype = $params['posttype']??1;
            if($posttype==2){
                $img = [];
                foreach ($data as $k => $v){
                    if (in_array($data[$k]->img, $img)){
                        $data[$k]->img = '';
                    }else{
                        $img[] = $data[$k]->img;
                    }
                }
                $p['title']='采购详情'.time();
                $p['title_list']  = [
                    'order_no' => '订单号',
                    'contract_no'=>'合同号',
                    'box_code'=>'中转任务号',
                    'custom_sku'=>'库存sku',
                    'img'=>'图片',
                    'spu'=>'spu',
                    'name'=>'颜色',
                    'identifying'=>'颜色标签',
                    'size'=>'尺码',
                    'transfers_num'=>'出库数量',
                    'receive_num'=>'实际接受数量',
                    'location_name'=>'库位',
                    'text' => '备注',
                    'createtime'=>'创建时间',
                ];
                $p['data'] = $data;
                // 更新单据出单状态
                db::table('goods_transfers')->where('order_no', $params['order_no'] ?? '')->update(['is_export' => 1]);
                $this->excel_expord($p);

//                $p['data'] =  $data;
//                $p['user_id'] = $params['find_user_id'];
//                $p['type'] = '采购详情-导出';
//                return $this->publicExport($p);
//                $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
//                try {
//                $job::runJob($p);
//                } catch(\Exception $e){
//                    return ['type' => 'fail', 'msg' => '加入队列失败'];
//                }
//                return ['type' => 'success','msg' => '加入队列成功'];

            }
            return ['code'=>200,'msg'=>['data'=>$data]];
        }else{
            return ['code'=>500,'msg'=>'没有入库单id'];
        }
    }

    public function goods_cloudOut($params)
    {
        if (!empty($params['request_id'])) {
            $list = DB::table('amazon_buhuo_request')->where('id', $params['request_id'])->select('id','request_status')->first();
            if (!empty($list)) {
                if ($list->request_status < 5) {
                    $arr['order_no'] = $params['request_id'];
                    $arr['type'] = 'B2BCK';
                    $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                    try {
                        $cloud::outhouseJob($arr);
                        Redis::Lpush('cloud_outRequest', $params['request_id']);
                        return ['code' => 200, 'msg' => '推送成功'];
                    } catch (\Exception $e) {
                        Redis::Lpush('out_house_fail', $params['request_id']);
                        return ['code' => 500, 'msg' => '推送失败'];
                    }
                } else {
                    return ['code' => 500, 'msg' => '云仓已接收此出库数据'];
                }
            } else {
                return ['code' => 500, 'msg' => '此出库单没有出库数据'];
            }

        }
    }

    public function getSaiheInventoryBySpu($params){

        $house_id = isset($params['house_id'])? $params['house_id'] : 1;
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        //初始化查询
        $thisDb = Db::table('self_spu');
        if(isset($params['spu'])){
            $spu = $params['spu'];
            $thisDb = $thisDb->where('spu','like','%'. $spu.'%')->orWhere('old_spu','like','%'. $spu.'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->where('one_cate_id','=',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->where('two_cate_id','=',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->where('three_cate_id','=',$params['three_cate_id']);
        }
        //数据总数
        $count=$thisDb->count();

        //执行查询
//        DB::connection()->enableQueryLog();
        $data = $thisDb->offset($page)->limit($limit)
            ->select('id','spu','one_cate_id','two_cate_id','three_cate_id','old_spu','user_id')
            ->orderby('spu','ASC')
            ->groupBy('spu')
            ->get()
            ->toArray();

//        var_dump(DB::getQueryLog());

        //取出新旧库存spu组合成数组
        $spuArr = array_column($data,'spu');


        //根据组合的库存sku数组查询赛盒同安fba仓，同安自发货仓，泉州仓库存
//        if($house_id==1){
//            $warehouse_id = [2,386];
//        }else{
//            $warehouse_id = [560];
//        }
//        $inventory = DB::table('saihe_inventory')->whereIn('spu',$spuArr)->whereIn('warehouse_id',$warehouse_id)->select('spu','good_num','warehouse_id')->get()->toArray();
        $fbaArr = [];
        $selfArr = [];
        $quanzhouArr = [];
        $newdata = [];
        //三个仓的库存分别组成数组
//        foreach ($inventory as $invenVal){
//            if($house_id==1){
//                if($invenVal->warehouse_id==2){
//                    $fbaArr[$invenVal->spu] = 0;
//                }
//                if($invenVal->warehouse_id==386){
//                    $selfArr[$invenVal->spu] = 0;
//                }
//            }else{
//                if($invenVal->warehouse_id==560){
//                    $quanzhouArr[$invenVal->spu] = 0;
//                }
//            }
//        }

//        foreach ($inventory as $invenVal){
//            if($house_id==1){
//                if($invenVal->warehouse_id==2){
//                    if(isset($fbaArr[$invenVal->spu])){
//                        $fbaArr[$invenVal->spu] += $invenVal->good_num;
//                    }else{
//                        $fbaArr[$invenVal->spu] = $invenVal->good_num;
//                    }
//                }
//                if($invenVal->warehouse_id==386){
//                    if(isset($selfArr[$invenVal->spu])){
//                        $selfArr[$invenVal->spu] += $invenVal->good_num;
//                    }else{
//                        $selfArr[$invenVal->spu] = $invenVal->good_num;
//                    }
//                    $selfArr[$invenVal->spu] += $invenVal->good_num;
//                }
//            }else{
//                if($invenVal->warehouse_id==560){
//                    if(isset($quanzhouArr[$invenVal->spu])){
//                        $quanzhouArr[$invenVal->spu] += $invenVal->good_num;
//                    }else{
//                        $quanzhouArr[$invenVal->spu] = $invenVal->good_num;
//                    }
//                }
//            }
//        }

        //查询库存sku的补货计划
        $buhuo_request = Db::table('amazon_buhuo_request as a')
            ->join('amazon_buhuo_detail as b','a.id','=','b.request_id')
            ->whereIn('b.spu',$spuArr)
            ->whereIn('a.request_status',[3,4,5,6,7])
            ->where('a.warehouse',$house_id)
            ->select('b.request_num','b.custom_sku', 'b.transportation_mode_name', 'b.transportation_type')
            ->get()->toArray();
        $courierArr = [];
        $shippingArr = [];
        $airArr = [];
        $kahangArr = [];
        $railwayArr = [];
        // 五种快递方式分别组成数组
        foreach ($buhuo_request as $requestVal){
            switch ($requestVal->transportation_type){
                case 1:
                    // 海运
                    if(isset($shippingArr[$requestVal->custom_sku])){
                        $shippingArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $shippingArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 2:
                    // 快递
                    if(isset($courierArr[$requestVal->custom_sku])){
                        $courierArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $courierArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 3:
                    // 空运
                    if(isset($airArr[$requestVal->custom_sku])){
                        $airArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $airArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 4:
                    // 铁路
                    if(isset($railwayArr[$requestVal->custom_sku])){
                        $railwayArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $railwayArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                case 5:
                    // 卡航
                    if(isset($kahangArr[$requestVal->custom_sku])){
                        $kahangArr[$requestVal->custom_sku] += $requestVal->request_num;
                    }else{
                        $kahangArr[$requestVal->custom_sku] = $requestVal->request_num;
                    }
                    break;
                default:
                    break;
            }
        }
        //赋值
        $customSkuMdl = DB::table('self_custom_sku')->get();
        foreach ($data as $key=>$val){
            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);
            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }
            //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }

            //图片
            $data[$key]->img = $this->GetSpuImg($val->spu);

            //运营
            $data[$key]->user = '';
            $account = $this->GetUsers($val->user_id);
            if($account){
                $data[$key]->user = $account['account'];
            }


            $data[$key]->inventory = 0;//库存

            //库存赋值
            $data[$key]->tongan_inventory = 0;
            $data[$key]->factory_num = 0;
            $data[$key]->quanzhou_inventory = 0;
            $data[$key]->deposit_inventory = 0;
            foreach ($customSkuMdl as $c){
                if ($c->spu_id == $val->id){
                    $data[$key]->tongan_inventory += $c->tongan_inventory;
                    $data[$key]->factory_num += $c->factory_num;
                    $data[$key]->quanzhou_inventory += $c->quanzhou_inventory;
                    $data[$key]->deposit_inventory += $c->deposit_inventory;
                }
            }


            //快递计划发货数量赋值
            if(array_key_exists($val->spu,$courierArr)){
                $data[$key]->courier_num = $courierArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$courierArr)){
                $data[$key]->courier_num = $courierArr[$val->old_spu];
            }else{
                $data[$key]->courier_num = 0;
            }
            //海运计划发货数量赋值
            if(array_key_exists($val->spu,$shippingArr)){
                $data[$key]->shipping_num = $shippingArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$shippingArr)){
                $data[$key]->shipping_num = $shippingArr[$val->old_spu];
            }else{
                $data[$key]->shipping_num = 0;
            }
            //空运计划发货数量赋值
            if(array_key_exists($val->spu,$airArr)){
                $data[$key]->air_num = $airArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$airArr)){
                $data[$key]->air_num = $airArr[$val->old_spu];
            }else{
                $data[$key]->air_num = 0;
            }
            // 铁路计划发货数量赋值
            if(array_key_exists($val->spu,$railwayArr)){
                $data[$key]->railway_num = $railwayArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$railwayArr)){
                $data[$key]->railway_num = $railwayArr[$val->old_spu];
            }else{
                $data[$key]->railway_num = 0;
            }
            // 卡航计划发货数量赋值
            if(array_key_exists($val->spu,$kahangArr)){
                $data[$key]->kahang_num = $kahangArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$kahangArr)){
                $data[$key]->kahang_num = $kahangArr[$val->old_spu];
            }else{
                $data[$key]->kahang_num = 0;
            }
            //计划发货数量合计
            $data[$key]->total_num = $data[$key]->courier_num+$data[$key]->shipping_num+$data[$key]->air_num+$data[$key]->railway_num+$data[$key]->kahang_num;
            //库存周转天数
            $data[$key]->turnover =  $data[$key]->total_num>0 ? round( $data[$key]->inventory/$data[$key]->total_num,2) : 0;

            $data[$key]->spu = $val->old_spu??$val->spu;



            $newdata[$key]['spu'] =  $data[$key]->spu;
            $newdata[$key]['inventory'] = $data[$key]->inventory;
            $newdata[$key]['air_num'] = $data[$key]->air_num;
            $newdata[$key]['courier_num'] =  $data[$key]->courier_num;
            $newdata[$key]['shipping_num'] =  $data[$key]->shipping_num;
            $newdata[$key]['total_num'] = $data[$key]->total_num;
            $newdata[$key]['turnover'] =  $data[$key]->turnover;

        }

        $posttype = isset($params['posttype']) ? $params['posttype'] : 1;


        if($house_id==1){
            $table_name = '同安';
        }else{
            $table_name = '泉州';
        }

        if($posttype==2){
            if(count($data)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']=$table_name.'SPU报表';
            $p['title_list']  = [
                'spu'=>'SPU',
                'inventory' => '库存',
                'air_num' => '空运',
                'courier_num' => '快递',
                'shipping_num' => '海运',
                'total_num' => '合计',
                'turnover' => '周转天数',
            ];
            $p['data'] =  $newdata;
            $this->excel_expord($p);
        }

        return [
            'data' => $data,
            'totalNum' => $count,
        ];
    }



    public function getSaiheInventoryByCate($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $house_id = $params['house_id'];

        if($house_id ==1){
            $cache = 'tongan';
        }else{
            $cache = 'quanzhou';
        }



        $list = Redis::Get('datacache:'.$cache.'InventoryCate');
        $newdata = Redis::Get('datacache:'.$cache.'InventoryCate_excel');
        if(!$list||!$newdata||isset($params['id'])||isset($params['cate_id'])&&$params['cate_id']!='undefined'){
            $thisDb = DB::table('self_category')->offset($page)->limit($limit);
            $type = 1;

            if(isset($params['id'])){
                $cate =  DB::table('self_category')->where('fid',$params['id'])->get()->toArray();
                $ids = array_column($cate,'Id');
                $thisDb ->whereIn('Id',$ids);
                $type = $cate[0]->type;
            }

            if(isset($params['cate_id'])&&$params['cate_id']!='undefined'){
                $thisDb = $thisDb->where('Id','=',$params['cate_id']);
                $list = $thisDb->get();
            }else{
                $list = $thisDb->where('type',$type)->get();
            }


            $count =  $thisDb->count();
            $newlist = [];
            $newdata = [];
            foreach ($list as $k => $v) {
                # code...
                if($v->type==1){
                    $v->hasChildren = true;
                    $query['one_cate_id'] = $v->Id;
                    $query['house_id'] = $house_id;
                    $res = $this->getSaiheInventoryByCateTotal($query);
                }
                if($v->type==2){
                    $v->hasChildren = true;
                    $query['two_cate_id'] = $v->Id;
                    $query['house_id'] = $house_id;
                    $res = $this->getSaiheInventoryByCateTotal($query);

                }
                if($v->type==3){
                    $v->hasChildren = false;
                    $query['three_cate_id'] = $v->Id;
                    $query['house_id'] = $house_id;
                    $res = $this->getSaiheInventoryByCateTotal($query);

                }

                $v->inventory = $res['inventory']??0;
                $v->air_num = $res['air_num']??0;
                $v->courier_num = $res['courier_num']??0;
                $v->shipping_num = $res['shipping_num']??0;
                $v->total_num = $res['total_num']??0;
                $v->turnover = $res['turnover']??0;

                $newdata[$k]['name'] = $v->name;
                $newdata[$k]['inventory'] = $v->inventory;
                $newdata[$k]['air_num'] = $v->air_num;
                $newdata[$k]['courier_num'] = $v->courier_num;
                $newdata[$k]['shipping_num'] = $v->shipping_num;
                $newdata[$k]['total_num'] = $v->total_num;
                $newdata[$k]['turnover'] = $v->turnover;

            }


            Redis::setex('datacache:'.$cache.'InventoryCate',3600*24,json_encode($list));
            Redis::setex('datacache:'.$cache.'InventoryCate_excel',3600*24,json_encode($newdata));
        }else{
            $list = json_decode($list,true);
            $newdata = json_decode($newdata);
            $count = count($list);
        }

        $posttype = isset($params['posttype']) ? $params['posttype'] : 1;


        if($house_id==1){
            $table_name = '同安';
        }else{
            $table_name = '泉州';
        }

        if($posttype==2){
            if(count($list)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']=$table_name.'分类报表';
            $p['title_list']  = [
                'name'=>'分类名',
                'inventory' => '库存',
                'air_num' => '空运',
                'courier_num' => '快递',
                'shipping_num' => '海运',
                'total_num' => '合计',
                'turnover' => '周转天数',
            ];
            $p['data'] =  $newdata;
            $this->excel_expord($p);
        }

        return [
            'data' => $list,
            'totalNum' => $count,
        ];

    }




    public function getSaiheInventoryByCateTotal($params){

        $house_id = isset($params['house_id'])? $params['house_id'] : 1;

        //根据组合的库存sku数组查询赛盒同安fba仓，同安自发货仓，泉州仓库存
        if(isset($params['one_cate_id'])){
            $query['one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $query['two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $query['three_cate_id'] = $params['three_cate_id'];
        }

        $res = DB::table('self_spu')->where($query)->get(['spu'])->toArray();

        $spuArr = array_column($res,'spu');


        if($house_id==1){
            $warehouse_id = [2,386];
        }else{
            $warehouse_id = [560];
        }


        $inventory = DB::table('saihe_inventory')->whereIn('spu',$spuArr)->whereIn('warehouse_id',$warehouse_id)->select('spu','good_num','warehouse_id')->get()->toArray();
        $inventorynum = 0;

        //三个仓的库存分别组成数组
        foreach ($inventory as $invenVal){
            $inventorynum+=$invenVal->good_num;
        }


        //查询库存sku的补货计划
        $buhuo_request = Db::table('amazon_buhuo_request as a')
            ->join('amazon_buhuo_detail as b','a.id','=','b.request_id')
            ->whereIn('b.spu',$spuArr)
            ->whereIn('a.request_status',[3,4,5,6,7])
            ->where('a.warehouse',$house_id)
            ->select('b.courier_num','b.shipping_num','b.air_num','b.spu')
            ->get()->toArray();
        $courier = 0;
        $shipping = 0;
        $air = 0;
        //三种快递方式分别组成数组
        foreach ($buhuo_request as $requestVal){

            $courier += $requestVal->courier_num;
            $shipping += $requestVal->shipping_num;
            $air += $requestVal->air_num;

        }


        //计划发货数量合计
        $total_num =$courier+ $shipping+ $air;
        //库存周转天数
        $turnover =  $total_num >0 ? round($inventorynum/ $total_num,2) : 0;

        $return['inventory'] = $inventorynum;
        $return['air_num'] = $air;
        $return['courier_num'] = $courier;
        $return['shipping_num'] = $shipping;
        $return['total_num'] = $total_num;
        $return['turnover'] = $turnover;
        return $return;
    }

    public function getInventoryByFasin($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        //初始化查询
        $thisDb = Db::table('product_detail as a')->leftjoin('amazon_link_ranklist as b','a.parent_asin','=','b.father_asin');
        if(isset($params['fasin'])){
            $fasin = $params['fasin'];
            $thisDb = $thisDb->where('a.parent_asin','like','%'.$fasin.'%');
        }
        if(isset($params['user_id'])){
            $thisDb = $thisDb->where('b.user_id','=',$params['user_id']);
        }



        //执行查询
//        DB::connection()->enableQueryLog();
        $thisDb = $thisDb->offset($page)->limit($limit)
            ->select('a.parent_asin as fasin','b.user_id','a.in_stock_num','a.in_bound_num','a.transfer_num','a.spu')
            ->groupBy('a.parent_asin');

        //数据总数
        $count=$thisDb->count();

        $data =$thisDb->get()
            ->toArray();

//        var_dump(DB::getQueryLog());
        $fasinarr = [];
        foreach ( $data as $key => $value) {
            # code...
            $fasinarr[$value->fasin]['in_stock_num'] = 0;
            $fasinarr[$value->fasin]['in_bound_num'] = 0;
            $fasinarr[$value->fasin]['transfer_num'] = 0;
            $fasinarr[$value->fasin]['spu'] = [];
        }

        foreach ( $data as $key => $value) {
            # code...
            $fasinarr[$value->fasin]['in_stock_num'] += $value->in_stock_num;
            $fasinarr[$value->fasin]['in_bound_num'] += $value->in_bound_num;
            $fasinarr[$value->fasin]['transfer_num'] += $value->transfer_num;
            $fasinarr[$value->fasin]['user_id'] =  $value->user_id;
            $fasinarr[$value->fasin]['fasin'] = $value->fasin;
            $fasinarr[$value->fasin]['spu'][] = $this->GetNewSpu($value->spu);
        }

        //取出新旧库存spu组合成数组
        $fasinarr_a = array_column($fasinarr,'fasin');
        // //查询库存
        // $product_detail = Db::table('product_detail')->whereIn('spu',$spuArr)->select('spu','in_stock_num','in_bound_num','transfer_num')->get()->toArray();
        //查询库龄
        $inventory_aged = Db::table('amazon_inventory_aged')->whereIn('father_asin',$fasinarr_a)->select('father_asin','day_0_90','day_91_180','day_181_270','day_271_365','day_365')->get()->toArray();
        $inven_age = [];//库龄数组  sku=>五种库龄数值

        foreach ($inventory_aged as $aged){
            $inven_age[$aged->father_asin] = ['day_0_90'=>$aged->day_0_90,'day_91_180'=>$aged->day_91_180,'day_181_270'=>$aged->day_181_270,'day_271_365'=>$aged->day_271_365,'day_365'=>$aged->day_365];
        }

        $fasinarr =  array_values($fasinarr);


        foreach ($fasinarr as $key =>$val){

            $fasin = $val['fasin'];

            $spus =  $val['spu'];

            $cus = DB::table('self_custom_sku')->whereIn('spu',$spus)->where('img','!=','')->first();
            $img = '';
            if($cus){
                $img = $cus->img;
            }

            $fasinarr[$key]['img'] = $img;
            unset($fasinarr[$key]['spu']);
            //运营
            $user = '';
            $account = $this->GetUsers($val['user_id']);
            if($account){
                $user = $account['account'];
            }

            $fasinarr[$key]['user_name'] = $user;
            //库龄赋值
            if(array_key_exists($fasin,$inven_age)){
                $fasinarr[$key]['day_0_90'] = $inven_age[$fasin]['day_0_90'];
                $fasinarr[$key]['day_91_180'] = $inven_age[$fasin]['day_91_180'];
                $fasinarr[$key]['day_181_270'] = $inven_age[$fasin]['day_181_270'];
                $fasinarr[$key]['day_271_365'] = $inven_age[$fasin]['day_271_365'];
                $fasinarr[$key]['day_365'] = $inven_age[$fasin]['day_365'];

            }else{
                $fasinarr[$key]['day_0_90'] = 0;
                $fasinarr[$key]['day_91_180'] = 0;
                $fasinarr[$key]['day_181_270'] = 0;
                $fasinarr[$key]['day_271_365'] = 0;
                $fasinarr[$key]['day_365'] = 0;
            }

        }
        $posttype = $params['posttype']??1;

        if($posttype==2){
            if(count($fasinarr)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']='海外仓fasin报表';
            $p['title_list']  = [
                'fasin'=>'父asin',
                'in_stock_num' => '可售',
                'in_bound_num' => '预留',
                'transfer_num' => '在途',
                'day_0_90' => '<90',
                'day_91_180' => '90-180',
                'day_181_270' => '180-270',
                'day_271_365' => '270',
                'day_365' => '>365',
            ];
            $p['data'] =  $fasinarr;
            $this->excel_expord($p);
        }



        return [
            'data' => $fasinarr,
            'totalNum' => $count,
        ];
    }




    public function getInventoryBySpu($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        //初始化查询
        $thisDb = Db::table('self_spu');
        if(isset($params['spu'])){
            $spu = $params['spu'];
            $thisDb = $thisDb->where('spu','like','%'. $spu.'%')->orWhere('old_spu','like','%'. $spu.'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->where('one_cate_id','=',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->where('two_cate_id','=',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->where('three_cate_id','=',$params['three_cate_id']);
        }
        //数据总数
        $count=$thisDb->count();

        //执行查询
//        DB::connection()->enableQueryLog();
        $data = $thisDb->offset($page)->limit($limit)
            ->select('spu','one_cate_id','two_cate_id','three_cate_id','old_spu','user_id')
            ->orderby('spu','ASC')
            ->groupBy('spu')
            ->get()
            ->toArray();


//        var_dump(DB::getQueryLog());

        //取出新旧库存spu组合成数组
        $spuArr=array_column($data,'spu');


        //查询库存
        $product_detail = Db::table('product_detail')->whereIn('spu',$spuArr)->select('spu','in_stock_num','in_bound_num','transfer_num')->get()->toArray();
        //查询库龄
        $inventory_aged = Db::table('amazon_inventory_aged')->whereIn('spu',$spuArr)->select('spu','day_0_90','day_91_180','day_181_270','day_271_365','day_365')->get()->toArray();
        $inven = [];//库存数组  sku=>三种库存
        foreach ($product_detail as $detail){
            if(isset($inven[$detail->spu])){
                $inven[$detail->spu]['in_stock_num']+=$detail->in_stock_num;
                $inven[$detail->spu]['in_bound_num']+=$detail->in_bound_num;
                $inven[$detail->spu]['transfer_num']+=$detail->transfer_num;
            }else{
                $inven[$detail->spu] = ['in_stock_num'=>$detail->in_stock_num,'in_bound_num'=>$detail->in_bound_num,'transfer_num'=>$detail->transfer_num];
            }
        }
        $inven_age = [];//库龄数组  sku=>五种库龄数值

        foreach ($inventory_aged as $aged){
            if(isset($inven_age[$aged->spu])){
                $inven_age[$aged->spu]['day_0_90']+=$aged->day_0_90;
                $inven_age[$aged->spu]['day_91_180']+=$aged->day_91_180;
                $inven_age[$aged->spu]['day_181_270']+=$aged->day_181_270;
                $inven_age[$aged->spu]['day_271_365']+=$aged->day_271_365;
                $inven_age[$aged->spu]['day_365']+=$aged->day_365;
            }else{
                $inven_age[$aged->spu] = ['day_0_90'=>$aged->day_0_90,'day_91_180'=>$aged->day_91_180,'day_181_270'=>$aged->day_181_270,'day_271_365'=>$aged->day_271_365,'day_365'=>$aged->day_365];
            }

        }

        $newdata = [];
        foreach ($data as $key =>$val){
            //图片
            $data[$key]->img = $this->GetSpuImg($val->spu);

            //运营
            $data[$key]->user = '';
            $account = $this->GetUsers($val->user_id);
            if($account){
                $data[$key]->user = $account['account'];
            }

            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);
            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }
            //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }
            //库存赋值
            if(array_key_exists($val->spu,$inven)){
                $data[$key]->in_stock_num = $inven[$val->spu]['in_stock_num'];
                $data[$key]->in_bound_num = $inven[$val->spu]['in_bound_num'];
                $data[$key]->transfer_num = $inven[$val->spu]['transfer_num'];
            }elseif(array_key_exists($val->old_spu,$inven)){
                $data[$key]->in_stock_num = $inven[$val->old_spu]['in_stock_num'];
                $data[$key]->in_bound_num = $inven[$val->old_spu]['in_bound_num'];
                $data[$key]->transfer_num = $inven[$val->old_spu]['transfer_num'];
            }else{
                $data[$key]->in_stock_num = 0;
                $data[$key]->in_bound_num = 0;
                $data[$key]->transfer_num = 0;
            }
            //库龄赋值
            if(array_key_exists($val->spu,$inven_age)){
                $data[$key]->day_0_90 = $inven_age[$val->spu]['day_0_90'];
                $data[$key]->day_91_180 = $inven_age[$val->spu]['day_91_180'];
                $data[$key]->day_181_270 = $inven_age[$val->spu]['day_181_270'];
                $data[$key]->day_271_365 = $inven_age[$val->spu]['day_271_365'];
                $data[$key]->day_365 = $inven_age[$val->spu]['day_365'];
            }elseif(array_key_exists($val->old_spu,$inven_age)){
                $data[$key]->day_0_90 = $inven_age[$val->old_spu]['day_0_90'];
                $data[$key]->day_91_180 = $inven_age[$val->old_spu]['day_91_180'];
                $data[$key]->day_181_270 = $inven_age[$val->old_spu]['day_181_270'];
                $data[$key]->day_271_365 = $inven_age[$val->old_spu]['day_271_365'];
                $data[$key]->day_365 = $inven_age[$val->old_spu]['day_365'];
            }else{
                $data[$key]->day_0_90 = 0;
                $data[$key]->day_91_180 = 0;
                $data[$key]->day_181_270 = 0;
                $data[$key]->day_271_365 = 0;
                $data[$key]->day_365 = 0;
            }

            if($val->old_spu!=null&&$val->old_spu!=''){
                $val->spu = $val->old_spu;
            }

            $newdata[$key]['spu'] =  $data[$key]->spu;
            $newdata[$key]['in_stock_num'] = $data[$key]->in_stock_num;
            $newdata[$key]['in_bound_num'] = $data[$key]->in_bound_num;
            $newdata[$key]['transfer_num'] = $data[$key]->transfer_num;
            $newdata[$key]['day_0_90'] = $data[$key]->day_0_90;
            $newdata[$key]['day_91_180'] = $data[$key]->day_91_180;
            $newdata[$key]['day_181_270'] = $data[$key]->day_181_270;
            $newdata[$key]['day_271_365'] = $data[$key]->day_271_365;
            $newdata[$key]['day_365'] = $data[$key]->day_365;

        }

        $posttype = isset($params['posttype']) ? $params['posttype'] : 1;

        if($posttype==2){
            if(count($data)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']='海外仓SPU报表';
            $p['title_list']  = [
                'spu'=>'SPU',
                'in_stock_num' => '可售',
                'in_bound_num' => '预留',
                'transfer_num' => '在途',
                'day_0_90' => '<90',
                'day_91_180' => '90-180',
                'day_181_270' => '180-270',
                'day_271_365' => '270',
                'day_365' => '>365',
            ];
            $p['data'] =  $newdata;
            $this->excel_expord($p);
        }


        return [
            'data' => $data,
            'totalNum' => $count,
        ];
    }



    public function getInventoryByCate($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $cache = 'haiwai';
        $list = Redis::get('datacache:'.$cache.'InventoryCate');
        $newdata = Redis::get('datacache:'.$cache.'InventoryCate_excel');
        if(!$list||!$newdata||isset($params['id'])||isset($params['cate_id'])&&$params['cate_id']!='undefined'){


            $thisDb = DB::table('self_category')->offset($page)->limit($limit);
            $type = 1;

            if(isset($params['id'])){
                $cate =  DB::table('self_category')->where('fid',$params['id'])->get()->toArray();
                $ids = array_column($cate,'Id');
                $thisDb ->whereIn('Id',$ids);
                $type = $cate[0]->type;
            }


            if(isset($params['cate_id'])&&$params['cate_id']!='undefined'){
                $thisDb = $thisDb->where('Id','=',$params['cate_id']);
                $list = $thisDb->get();
            }else{
                $list = $thisDb->where('type',$type)->get();
            }

            $count =  $thisDb->count();
            $newdata = [];

            foreach ($list as $k => $v) {
                # code...
                if($v->type==1){
                    $query['one_cate_id'] = $v->Id;
                    $res = $this->getInventoryByCateTotal($query);
                    $v->hasChildren = true;
                }
                if($v->type==2){
                    $query['two_cate_id'] = $v->Id;
                    $res = $this->getInventoryByCateTotal($query);
                    $v->hasChildren = true;

                }
                if($v->type==3){
                    $query['three_cate_id'] = $v->Id;
                    $res = $this->getInventoryByCateTotal($query);
                    $v->hasChildren = false;

                }
                $v->in_stock_num = $res['in_stock_num']??0;
                $v->in_bound_num = $res['in_bound_num']??0;
                $v->transfer_num = $res['transfer_num']??0;
                $v->day_0_90 = $res['day_0_90']??0;
                $v->day_91_180 = $res['day_91_180']??0;
                $v->day_181_270 = $res['day_181_270']??0;
                $v->day_271_365 = $res['day_271_365']??0;
                $v->day_365 = $res['day_365']??0;

                $newdata[$k]['name'] = $v->name;
                $newdata[$k]['in_stock_num'] = $v->in_stock_num;
                $newdata[$k]['in_bound_num'] = $v->in_bound_num;
                $newdata[$k]['transfer_num'] = $v->transfer_num;
                $newdata[$k]['day_0_90'] = $v->day_0_90;
                $newdata[$k]['day_91_180'] = $v->day_91_180;
                $newdata[$k]['day_181_270'] = $v->day_181_270;
                $newdata[$k]['day_271_365'] = $v->day_271_365;
                $newdata[$k]['day_365'] = $v->day_365 ;

            }
            Redis::setex('datacache:'.$cache.'InventoryCate',3600*24,json_encode($list));
            Redis::setex('datacache:'.$cache.'InventoryCate_excel',3600*24,json_encode($newdata));
        }else{
            $list = json_decode($list,true);
            $newdata = json_decode($newdata);
            $count = count($list);
        }
        $posttype = isset($params['posttype']) ? $params['posttype'] : 1;

        if($posttype==2){
            if(count($list)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']='海外仓SPU报表';
            $p['title_list']  = [
                'name'=>'分类名',
                'in_stock_num' => '可售',
                'in_bound_num' => '预留',
                'transfer_num' => '在途',
                'day_0_90' => '<90',
                'day_91_180' => '90-180',
                'day_181_270' => '180-270',
                'day_271_365' => '270',
                'day_365' => '>365',
            ];
            $p['data'] =  $newdata;
            $this->excel_expord($p);
        }
        return [
            'data' => $list,
            'totalNum' => $count,
        ];

    }


    public function getInventoryByCateTotal($params){

        $house_id = isset($params['house_id'])? $params['house_id'] : 1;

        //根据组合的库存sku数组查询赛盒同安fba仓，同安自发货仓，泉州仓库存
        if(isset($params['one_cate_id'])){
            $query['one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $query['two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $query['three_cate_id'] = $params['three_cate_id'];
        }

        $res = DB::table('self_spu')->where($query)->get(['spu','old_spu'])->toArray();

        $spuarr = array_column($res,'spu');
        $old_spuarr = array_column($res,'old_spu');

        $spuArr=array_merge($spuarr,$old_spuarr);

        //查询库存
        $product_detail = Db::table('product_detail')->whereIn('spu',$spuArr)->select('spu','in_stock_num','in_bound_num','transfer_num')->get()->toArray();
        //查询库龄
        $inventory_aged = Db::table('amazon_inventory_aged')->whereIn('spu',$spuArr)->select('spu','day_0_90','day_91_180','day_181_270','day_271_365','day_365')->get()->toArray();
        $in_stock_num = 0;
        $in_bound_num = 0;
        $transfer_num = 0;
        foreach ($product_detail as $detail){
            $in_stock_num +=$detail->in_stock_num;
            $in_bound_num +=$detail->in_bound_num;
            $transfer_num +=$detail->transfer_num;
        }

        $day_0_90 = 0;
        $day_91_180 = 0;
        $day_181_270 = 0;
        $day_271_365 = 0;
        $day_365 = 0;

        foreach ($inventory_aged as $aged){
            $day_0_90 +=$aged->day_0_90;
            $day_91_180 +=$aged->day_91_180;
            $day_181_270 +=$aged->day_181_270;
            $day_271_365 +=$aged->day_271_365;
            $day_365 +=$aged->day_365;

        }

        $return['in_stock_num'] = $in_stock_num;
        $return['in_bound_num'] = $in_bound_num;
        $return['transfer_num'] = $transfer_num;
        $return['day_0_90'] = $day_0_90;
        $return['day_91_180'] = $day_91_180;
        $return['day_181_270'] = $day_181_270;
        $return['day_271_365'] = $day_271_365;
        $return['day_365'] = $day_365;
        return $return;
    }



    public function getCloudInventoryBySpu($params){


        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        //初始化查询
        $thisDb = Db::table('self_spu');
        if(isset($params['spu'])){
            $spu = $params['spu'];
            $thisDb = $thisDb->where('spu','like','%'. $spu.'%')->orWhere('old_spu','like','%'. $spu.'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->where('one_cate_id','=',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->where('two_cate_id','=',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->where('three_cate_id','=',$params['three_cate_id']);
        }
        //数据总数
        $count=$thisDb->count();

        //执行查询
//        DB::connection()->enableQueryLog();
        $data = $thisDb->offset($page)->limit($limit)
            ->select('spu','one_cate_id','two_cate_id','three_cate_id','old_spu','user_id')
            ->orderby('spu','ASC')
            ->groupBy('spu')
            ->get()
            ->toArray();


//        var_dump(DB::getQueryLog());

        //取出新旧库存spu组合成数组
        $spuArr= array_column($data,'spu');

        //根据组合的库存sku数组查询赛盒同安fba仓，同安自发货仓，泉州仓库存

        //查询库存sku的补货计划
        $buhuo_request = Db::table('amazon_buhuo_request as a')
            ->join('amazon_buhuo_detail as b','a.id','=','b.request_id')
            ->whereIn('b.spu',$spuArr)
            ->whereIn('a.request_status',[3,4,5,6,7])
            ->where('a.warehouse',3)
            ->select('b.courier_num','b.shipping_num','b.air_num','spu')
            ->get()->toArray();
        $courierArr = [];
        $shippingArr = [];
        $airArr = [];
        $newdata = [];
        //三种快递方式分别组成数组

        foreach ($buhuo_request as $requestVal){
            if($requestVal->spu){
                if(isset($courierArr[$requestVal->spu])){
                    $courierArr[$requestVal->spu] += $requestVal->courier_num;
                }else{
                    $courierArr[$requestVal->spu] = $requestVal->courier_num;
                }
                if(isset($shippingArr[$requestVal->spu])){
                    $shippingArr[$requestVal->spu] += $requestVal->courier_num;
                }else{
                    $shippingArr[$requestVal->spu] = $requestVal->courier_num;
                }
                if(isset($airArr[$requestVal->spu])){
                    $airArr[$requestVal->spu] += $requestVal->courier_num;
                }else{
                    $airArr[$requestVal->spu] = $requestVal->courier_num;
                }
            }
        }
        //赋值
        foreach ($data as $key=>$val){

            //图片
            $data[$key]->img = $this->GetSpuImg($val->spu);

            //运营
            $data[$key]->user = '';
            $account = $this->GetUsers($val->user_id);
            if($account){
                $data[$key]->user = $account['account'];
            }

            //大类
            $val->one_cate = '';
            $one_cate = $this->GetCategory($val->one_cate_id);
            if($one_cate){
                $val->one_cate = $one_cate['name'];
            }
            //二类
            $val->two_cate = '';
            $two_cate = $this->GetCategory($val->two_cate_id);
            if($two_cate){
                $val->two_cate = $two_cate['name'];
            }
            //三类
            $val->three_cate = '';
            $three_cate = $this->GetCategory($val->three_cate_id);
            if($three_cate){
                $val->three_cate = $three_cate['name'];
            }

            $data[$key]->inventory = 0;//库存

            //库存

            $cus = Db::table('self_custom_sku')->where('spu',$val->old_spu)->orwhere('spu',$val->spu)->get();
            $inventory = 0;
            foreach ($cus as $cusres) {
                # code...
                $inventory+=$cusres->cloud_num;
            }

            $data[$key]->inventory =  $inventory;

            //快递计划发货数量赋值
            if(array_key_exists($val->spu,$courierArr)){
                $data[$key]->courier_num = $courierArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$courierArr)){
                $data[$key]->courier_num = $courierArr[$val->old_spu];
            }else{
                $data[$key]->courier_num = 0;
            }
            //海运计划发货数量赋值
            if(array_key_exists($val->spu,$shippingArr)){
                $data[$key]->shipping_num = $shippingArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$shippingArr)){
                $data[$key]->shipping_num = $shippingArr[$val->old_spu];
            }else{
                $data[$key]->shipping_num = 0;
            }
            //空运计划发货数量赋值
            if(array_key_exists($val->spu,$airArr)){
                $data[$key]->air_num = $airArr[$val->spu];
            }elseif(array_key_exists($val->old_spu,$airArr)){
                $data[$key]->air_num = $airArr[$val->old_spu];
            }else{
                $data[$key]->air_num = 0;
            }
            //计划发货数量合计
            $data[$key]->total_num = $data[$key]->courier_num+$data[$key]->shipping_num+$data[$key]->air_num;
            //库存周转天数
            $data[$key]->turnover =  $data[$key]->total_num>0 ? round( $data[$key]->inventory/$data[$key]->total_num,2) : 0;

            $data[$key]->spu = $val->old_spu??$val->spu;

            $newdata[$key]['spu'] =  $data[$key]->spu;
            $newdata[$key]['inventory'] = $data[$key]->inventory;
            $newdata[$key]['air_num'] = $data[$key]->air_num;
            $newdata[$key]['courier_num'] =  $data[$key]->courier_num;
            $newdata[$key]['shipping_num'] =  $data[$key]->shipping_num;
            $newdata[$key]['total_num'] = $data[$key]->total_num;
            $newdata[$key]['turnover'] =  $data[$key]->turnover;

        }

        $posttype = isset($params['posttype']) ? $params['posttype'] : 1;


        if($posttype==2){
            if(count($data)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']='云仓SPU报表';
            $p['title_list']  = [
                'spu'=>'SPU',
                'inventory' => '库存',
                'air_num' => '空运',
                'courier_num' => '快递',
                'shipping_num' => '海运',
                'total_num' => '合计',
                'turnover' => '周转天数',
            ];
            $p['data'] =  $newdata;
            $this->excel_expord($p);
        }

        return [
            'data' => $data,
            'totalNum' => $count,
        ];
    }


    //获取出库类型
    public function GetOutTypeDetail($params){
        $arr = $this->GetFieldOutTypeDetailArr();
        $datas = [];
        foreach ($arr as $key => $value) {
            # code...
            $data['type'] = $key;
            $data['type_name'] = $value;
            $datas[] = $data;
        }
        return ['type'=>'success','data'=>$datas];
    }


    //app出库清单
    public function GetOutPushOrder($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $list = DB::table('goods_transfers');
        $count = $list->count();
        $list =$list->whereIn('type_detail',$this->GetfieldTypeDetail());
    
        if(isset($params['is_push'])){
            $list =$list->where('is_push',$params['is_push']);
        }

        if(isset($params['warehouse_id'])){
            $list =$list->where('out_house',$params['warehouse_id']);
        }
        
        if(isset($params['type_detail'])){
            $list =$list->where('type_detail',$params['type_detail']);
        }
        


        $order_nos = [];
        if(isset($params['task_user'])){
            $user = db::table('users')->where('account','like','%'.$params['task_user'].'%')->get()->toArray();
            if($user){
                $user_ids = array_column($user,'Id');
                $task_son_res = db::table('tasks_son')->whereIn('user_id',$user_ids)->where('state',1)->get()->toArray();
                $task_ids = array_column($task_son_res,'task_id');
                $task_res = db::table('tasks')->whereIn('Id',$task_ids)->get();

                foreach ($task_res as $v) {
                 # code...
                     $tasks_node = db::table('tasks_node')->where('task_id',$v->Id)->where('state',2)->select('id')->first();
                     if($tasks_node){
                         $ext = json_decode($v->ext,true);
                         if(isset($ext['request_id'])){
                             $order_nos[] = $ext['request_id'];
                         }
                         if(isset($ext['transfers_id'])){
                             $order_nos[] = $ext['transfers_id'];
                         }
                     }
                }
            }


            if(count($order_nos)>0){
                $list =$list->whereIn('order_no',$order_nos);
            }else{
                return [
                    'data' => [],
                    'totalNum' => 0,
                    'msg'=>'获取成功',
                ];
            }
        }

        if($params['is_push']==3){
            $list =$list->offset($page)->limit($limit)->select('order_no','user_id','shop_id','type_detail')->orderby('createtime','desc')->get();
        }else{
            $list =$list->offset($page)->limit($limit)->select('order_no','user_id','shop_id','type_detail')->orderby('createtime','asc')->get();
        }

        foreach ($list as $v) {
            # code...
            $v->user_name = $this->GetUsers($v->user_id)['account'];
            $v->shop_name = $this->GetShop($v->shop_id)['shop_name'];
            $v->type = $this->GetFieldTypeDetailArr()[$v->type_detail];
            $v->task_user = '';
            $task = db::table('tasks')->where('ext','like','%'.$v->order_no.'%')->first();
            if($task){
                $task_node = db::table('tasks_node')->where('task_id',$task->Id)->first();
                $task_son = db::table('tasks_son')->where('task_id',$task->Id)->first();
                if($task_son){
                    $v->task_user = $this->GetUsers($task_son->user_id)['account'];
                }
                if($task_node){
                    if($task_node->state<2){
                        unset($v);
                    }
                }
            }
        }

        return [
            'data' => $list,
            'totalNum' => $count,
            'msg'=>'获取成功',
        ];

    }


    public function getCloudInventoryByCate($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;



        //分页
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $cache = "cloud";
        $list = Redis::Get('datacache:'.$cache.'InventoryCate');
        $newdata = Redis::Get('datacache:'.$cache.'InventoryCate_excel');
        if(!$list||!$newdata||isset($params['id'])||isset($params['cate_id'])&&$params['cate_id']!='undefined'){

            $thisDb = DB::table('self_category')->offset($page)->limit($limit);
            $type = 1;


            if(isset($params['id'])){
                $cate =  DB::table('self_category')->where('fid',$params['id'])->get()->toArray();
                $ids = array_column($cate,'Id');
                $thisDb ->whereIn('Id',$ids);
                $type = $cate[0]->type;
            }


            if(isset($params['cate_id'])&&$params['cate_id']!='undefined'){
                $thisDb = $thisDb->where('Id','=',$params['cate_id']);
                $list = $thisDb->get();
            }else{
                $list = $thisDb->where('type',$type)->get();
            }

            $count =  $thisDb->count();
            $newdata=[];
            foreach ($list as $k => $v) {
                # code...
                if($v->type==1){
                    $query['one_cate_id'] = $v->Id;
                    $res = $this->getCloudInventoryByCateTotal($query);
                    $v->hasChildren = true;
                }
                if($v->type==2){
                    $query['two_cate_id'] = $v->Id;
                    $res = $this->getCloudInventoryByCateTotal($query);
                    $v->hasChildren = true;

                }
                if($v->type==3){
                    $query['three_cate_id'] = $v->Id;
                    $res = $this->getCloudInventoryByCateTotal($query);
                    $v->hasChildren = false;

                }

                $v->inventory = $res['inventory']??0;
                $v->air_num = $res['air_num']??0;
                $v->courier_num = $res['courier_num']??0;
                $v->shipping_num = $res['shipping_num']??0;
                $v->total_num = $res['total_num']??0;
                $v->turnover = $res['turnover']??0;

                $newdata[$k]['name'] = $v->name;
                $newdata[$k]['inventory'] = $v->inventory;
                $newdata[$k]['air_num'] = $v->air_num;
                $newdata[$k]['courier_num'] = $v->courier_num;
                $newdata[$k]['shipping_num'] = $v->shipping_num;
                $newdata[$k]['total_num'] = $v->total_num;
                $newdata[$k]['turnover'] = $v->turnover;

            }
            Redis::setex('datacache:'.$cache.'InventoryCate',3600*24,json_encode($list));
            Redis::setex('datacache:'.$cache.'InventoryCate_excel',3600*24,json_encode($newdata));
        }else{
            $list = json_decode($list,true);
            $newdata = json_decode($newdata);
            $count = count($list);
        }
        $posttype = isset($params['posttype']) ? $params['posttype'] : 1;
        if($posttype==2){
            if(count($list)>10000){
                return ['type' => 'fail', 'msg' => '无法导出1万条以上数据'];
            }
            $p['title']='云仓分类报表';
            $p['title_list']  = [
                'name'=>'分类名',
                'inventory' => '库存',
                'air_num' => '空运',
                'courier_num' => '快递',
                'shipping_num' => '海运',
                'total_num' => '合计',
                'turnover' => '周转天数',
            ];
            $p['data'] =  $newdata;
            $this->excel_expord($p);
        }

        return [
            'data' => $list,
            'totalNum' => $count,
        ];

    }


    public function getCloudInventoryByCateTotal($params){

        //根据组合的库存sku数组查询赛盒同安fba仓，同安自发货仓，泉州仓库存
        if(isset($params['one_cate_id'])){
            $query['one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $query['two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $query['three_cate_id'] = $params['three_cate_id'];
        }

        $res = DB::table('self_spu')->where($query)->get(['spu','old_spu'])->toArray();

        $spuarr = array_column($res,'spu');
        $old_spuarr = array_column($res,'old_spu');

        $spuArr=array_merge($spuarr,$old_spuarr);




        $inventory = DB::table('self_custom_sku')->whereIn('spu',$spuArr)->select('spu','cloud_num')->get()->toArray();
        $inventorynum = 0;

        //三个仓的库存分别组成数组
        foreach ($inventory as $invenVal){
            $inventorynum+=$invenVal->cloud_num;
        }

        //查询库存sku的补货计划
        $buhuo_request = Db::table('amazon_buhuo_request as a')
            ->join('amazon_buhuo_detail as b','a.id','=','b.request_id')
            ->whereIn('b.spu',$spuArr)
            ->whereIn('a.request_status',[3,4,5,6,7])
            ->where('a.warehouse',3)
            ->select('b.courier_num','b.shipping_num','b.air_num','spu')
            ->get()->toArray();
        $courier = 0;
        $shipping = 0;
        $air = 0;
        //三种快递方式分别组成数组
        foreach ($buhuo_request as $requestVal){

            $courier += $requestVal->courier_num;
            $shipping += $requestVal->shipping_num;
            $air += $requestVal->air_num;

        }


        //计划发货数量合计
        $total_num =$courier+ $shipping+ $air;
        //库存周转天数
        $turnover =  $total_num >0 ? round($inventorynum/ $total_num,2) : 0;

        $return['inventory'] = $inventorynum;
        $return['air_num'] = $air;
        $return['courier_num'] = $courier;
        $return['shipping_num'] = $shipping;
        $return['total_num'] = $total_num;
        $return['turnover'] = $turnover;
        return $return;
    }


    public function confirmInhouse($params){
        $token = isset($params['token'])?$params['token']:'';
        $user_id = 1;
        //根据token识别申请人
        if(!empty($token)){
            $user_data = DB::table('users')->where('token', '=', $token)->select('Id')->first();
            if(!empty($user_data)){
                $user_id = $user_data->Id;
            }
        }
        $order_no = $params['order_no'];
        $goods_transfers = DB::table('goods_transfers')->where('order_no',$order_no)->first();

        if(empty($goods_transfers)){
            return ['code'=>500,'msg'=>'没有此单号的数据'];
        }
        if($goods_transfers->type_detail==6){
            return ['code'=>500,'msg'=>'fba出库无法在此处确认'];
        }
        if($goods_transfers->is_push!=4){
            if($goods_transfers->in_house<6&&$goods_transfers->out_house<6){
                return ['code'=>500,'msg'=>'当前订单状态不可确认'];
            }
        }
        if(isset($params['data'])){
            $data = json_decode($params['data'],true);
        }else{
            $goods_transfers_detail = DB::table('goods_transfers_detail')->where('order_no',$order_no)->get();
            $data = json_decode(json_encode($goods_transfers_detail),true);
            foreach ($data as $kk=>$dd){
                $data[$kk]['receive_num'] = $dd['transfers_num'];
            }
        }
        $spuIds = array_column($data,'spu_id');
        $spuIds = array_unique($spuIds);
        $spudata = DB::table('self_spu')->whereIn('id',$spuIds)->select('base_spu_id')->get()->toArray();
        $baseSpu = array_column($spudata,'base_spu_id');
        $priceArr = [];
        if(!empty($baseSpu)){
            $baseSpu = array_unique($baseSpu);
            $spuInfo = DB::table('self_spu_info')->whereIn('base_spu_id',$baseSpu)->select('unit_price','base_spu_id')->get()->toArray();
            if(!empty($spuInfo)){
                foreach ($spuInfo as $info){
                    $priceArr[$info->base_spu_id] = $info->unit_price;
                }
            }
        }



        if($goods_transfers->type_detail>6&&$goods_transfers->type_detail<13){
            if($goods_transfers->out_house==1||$goods_transfers->out_house==2){
                $goods_transfers_box = DB::table('goods_transfers_box')->where('order_no',$order_no)->select('onshelf_num')->first();

                if(!empty($goods_transfers_box)){
                    $on_shelf_num = $goods_transfers_box->onshelf_num;
                }else{
                    return ['code'=>500,'msg'=>'未获取到中转任务'];
                }
            }
        }

        db::beginTransaction();
        $receive_total = 0;
        $usable_total = 0;
        $unable_total = 0;
        $date = date('Y-m-d H:i:s');

        //同步库存到翎星
        if ($goods_transfers->platform_id == 5) {
            $lxParams      = [
                'wid'          => 0,
                'type'         => 0,
                'product_list' => [],
            ];
            $customSkuList = DB::table('self_custom_sku')->whereIn('id', array_column($data, 'custom_sku_id'))->pluck('custom_sku', 'id');
        }
        $factoryArr = [6,21,23];
        if(in_array($goods_transfers->in_house,$factoryArr)||in_array($goods_transfers->out_house,$factoryArr)){
            $contract_json = json_decode($goods_transfers->contract_no,true);
            $suppliers = DB::table('cloudhouse_contract_total as a')->leftJoin('suppliers as b','a.supplier_id','=','b.Id')
                ->where('contract_no', $contract_json[0])
                ->select('b.supplier_no')->first();
            $factoryData =  DB::table('cloudhouse_warehouse_location')
                ->where('location_name',$suppliers->supplier_no)
                ->where('level',3);
        }
        if(in_array($goods_transfers->in_house,$factoryArr)){
            $factoryData = $factoryData
                ->where('warehouse_id',$goods_transfers->in_house)
                ->select('id')
                ->first();
            if(empty($factoryData)){
                return ['code'=>500,'msg'=>'没有此供应商的库位'];
            }
            $factoryIn = $factoryData->id;
        }
        if(in_array($goods_transfers->out_house,$factoryArr)){
            $factoryData = $factoryData
                ->where('warehouse_id',$goods_transfers->out_house)
                ->select('id')
                ->first();
            if(empty($factoryData)){
                return ['code'=>500,'msg'=>'没有此供应商的库位'];
            }
            $factoryOut = $factoryData->id;
        }
        foreach ($data as $v) {
            if ($v['receive_num'] != 0) {
                $inven = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->first();
                if (empty($inven) ) {
                    db::rollback();// 回调
                    return ['code' => 500, 'msg' => '系统没有id是' . $v['custom_sku_id'] . '的sku'];
                }
                $invenJson = json_decode(json_encode($inven),true);
                if(isset($v['usable_num'])&&isset($v['unable_num'])){
                    if(!in_array($goods_transfers->type_detail,$this->GetFieldTypeDetail2())){
                        $update = DB::table('goods_transfers_detail')->where('id', $v['id'])->update(['receive_num' => $v['receive_num'],'usable_num' => $v['usable_num'],'unable_num'=>$v['unable_num']]);
                        if (!$update) {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => $order_no . '的' . $v['custom_sku'] . '接收数据失败'];
                        }
                    }
                    
                    if($v['usable_num']>0){
                        $usable_total += $v['usable_num'];
                        if($goods_transfers->type_detail==15){
                            $change['data'][] = ['num'=>$v['usable_num'],'id'=>$inven->id,'custom_sku'=>$inven->custom_sku,'spu'=>$inven->spu];
                        }
                    }
                    if($v['unable_num']>0){
                        $unable_total += $v['unable_num'];
                        if($goods_transfers->type_detail==15){
                            $change3['data'][] = ['num'=>$v['unable_num'],'id'=>$inven->id,'custom_sku'=>$inven->custom_sku,'spu'=>$inven->spu];
                        }
                    }

                    if($goods_transfers->type_detail==15){
                        if($v['receive_num']-$v['usable_num']-$v['unable_num']>0){
                            $change2['data'][] = ['num'=>$v['receive_num']-$v['usable_num']-$v['unable_num'],'id'=>$inven->id,'custom_sku'=>$inven->custom_sku,'spu'=>$inven->spu];

                        }
                    }
                }else{
                    if($goods_transfers->type_detail==17){
                        $transfers_detail = DB::table('goods_transfers_detail')->where('custom_sku_id', $v['custom_sku_id'])->where('order_no', $order_no)
                            ->select('transfers_num','receive_num','id')
                            ->get();
                        $detailCount = count($transfers_detail);
                        if($detailCount>1) {
                            $receiveNum = $v['receive_num'];
                            for($i=0;$i<$detailCount;$i++){
                                if($receiveNum>0){
                                    if($receiveNum>$transfers_detail[$i]->transfers_num){
                                        DB::table('goods_transfers_detail')->where('id', $transfers_detail[$i]->id)->update(['receive_num' => $transfers_detail[$i]->transfers_num]);
                                    }else{
                                        DB::table('goods_transfers_detail')->where('id', $transfers_detail[$i]->id)->update(['receive_num' => $receiveNum]);
                                    }
                                    $receiveNum -= $transfers_detail[$i]->transfers_num;
                                }
                            }
                        } else{
                            $update = DB::table('goods_transfers_detail')->where('id', $v['id'])->update(['receive_num' => $v['receive_num']]);
                            if (!$update) {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => $order_no . '的' . $v['custom_sku'] . '接收数据失败'];
                            }
                        }
                    }elseif(!in_array($goods_transfers->type_detail,$this->GetFieldTypeDetail2())){
                        $update = DB::table('goods_transfers_detail')->where('id', $v['id'])->update(['receive_num' => $v['receive_num']]);
                        if (!$update) {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => $order_no . '的' . $v['custom_sku'] . '接收数据失败'];
                        }
                    }elseif($goods_transfers->type_detail==2){
                        //采购入库工厂直发仓或者工厂寄存仓不用上架直接入库
                        if($goods_transfers->in_house==6||$goods_transfers->in_house==21){
                            $update = DB::table('goods_transfers_detail')->where('id', $v['id'])->update(['receive_num' => $v['receive_num']]);
                            if (!$update) {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => $order_no . '的' . $v['custom_sku'] . '接收数据失败'];
                            }
                        }
                    }

                }



                $insert['order_no'] = $order_no;
                $insert['spu'] = $v['spu'];
                $insert['spu_id'] = $v['spu_id'];
                $insert['custom_sku'] = $v['custom_sku'];
                $insert['custom_sku_id'] = $v['custom_sku_id'];
                $insert['num'] = $v['receive_num'];
                $insert['createtime'] = $date;
                $insert['user_id'] = $user_id;


                if ($goods_transfers->type == 1) {
                    //查询合同单价
                    $custom_sku_pirce = DB::table('cloudhouse_custom_sku')->where('custom_sku_id',$v['custom_sku_id'])
                        ->where('contract_no',$v['contract_no'])->select('price')->first();
                    if(empty($custom_sku_pirce)){
                        db::rollback();// 回调
                        return ['code' => 500, 'msg' => '未查询到合同单价--' . $v['custom_sku']];
                    }
                    $query['price'] = $custom_sku_pirce->price;
                    if($query['price']==0){
                        if (isset($priceArr[$inven->base_spu_id])){
                            $query['price'] = $priceArr[$inven->base_spu_id];
                        }
                    }
                    //查询单价end

                    if ($goods_transfers->type_detail == 2) {
                        //采购入库确认出货数据
                        $insert['warehouse_id'] = $goods_transfers->in_house;
                        $insert['type'] = 2;
                        if(isset($factoryIn)){
                            $location_num = DB::table('cloudhouse_location_num')->where('custom_sku_id', $v['custom_sku_id'])->where('location_id',$factoryIn)
                                ->where('platform_id',$goods_transfers->platform_id)->select('id','num')->first();
                            if(!empty($location_num)){
                                $update_location = DB::table('cloudhouse_location_num')->where('id', $location_num->id)->update(['num'=>$location_num->num+$v['receive_num']]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位入库失败--' . $v['custom_sku']];
                                }
                            }else{
                                $insert_location = DB::table('cloudhouse_location_num')->insert([
                                    'custom_sku_id'=>$v['custom_sku_id'],
                                    'spu_id'=>$invenJson['spu_id'],
                                    'custom_sku'=>$invenJson['custom_sku'],
                                    'spu'=>$invenJson['spu'],
                                    'num'=>$v['receive_num'],
                                    'platform_id'=>$goods_transfers->platform_id,
                                    'location_id'=>$factoryIn,
                                    'create_time'=>time(),
                                ]);
                                if(!$insert_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位入库失败--' . $v['custom_sku']];
                                }
                            }
                            $query['warehouse_id'] = $goods_transfers->in_house;
                            $query['custom_sku_id'] = $v['custom_sku_id'];

                            $query['num'] = $v['receive_num'];
                            $query['user_id'] = $user_id;
                            $query['type'] = 2; //1为出2为入
                            $res = $this->UpCloudHousePrice($query);
                            if ($res['type'] != 'success') {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                            }
                            $insert['type_detail'] = $goods_transfers->type_detail;
                            $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->in_house]] + $v['receive_num'];
                            $modify1Update[self::WAREHOUSE[$goods_transfers->in_house]] = $reduce_num;
                            $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);
                            $insert['shop_id'] = $goods_transfers->shop_id;
                            $insert['price'] = $query['price'];
                            $insert['now_inventory'] = $reduce_num;
                            $insert['now_total_price'] = $res['total_price'];
                            $insertIn = DB::table('cloudhouse_record')->insert($insert);
                            if (!$insertIn) {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '新增出库记录失败--' . $v['custom_sku']];
                            }

                        }
                    } else {
                        //采购单退货
                        $query['warehouse_id'] = $goods_transfers->out_house;
                        $query['custom_sku_id'] = $v['custom_sku_id'];
                        $query['num'] = $v['receive_num'];
                        $query['user_id'] = $user_id;
                        $query['type'] = 1; //1为出2为入
                        $res = $this->UpCloudHousePrice($query);
                        if ($res['type'] != 'success') {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                        }
                        $insert['type'] = 1;
                        $insert['type_detail'] = 9;
                        $insert['warehouse_id'] = $goods_transfers->out_house;

                        $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->out_house]] - $v['receive_num'];
                        $modify1Update[self::WAREHOUSE[$goods_transfers->out_house]] = $reduce_num;
                        $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);

                        $insert['price'] = $query['price'];
                        $insert['now_inventory'] = $reduce_num;
                        $insert['now_total_price'] = $res['total_price'];

                        $insertOut = DB::table('cloudhouse_record')->insert($insert);
                        if (!$insertOut) {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增出库记录失败--' . $v['custom_sku']];
                        }

                    }
                } elseif ($goods_transfers->type == 2) {
                    //订单出入库
                    if ($goods_transfers->type_detail == 12||$goods_transfers->type_detail == 8) {
                        $query['warehouse_id'] = $goods_transfers->out_house;
                        $query['custom_sku_id'] = $v['custom_sku_id'];
                        $query['price'] = $this->GetCloudHousePrice($goods_transfers->out_house, $v['custom_sku_id']);
                        $query['num'] = $v['receive_num'];
                        $query['user_id'] = $user_id;
                        $query['type'] = 1; //1为出2为入
                        $res = $this->UpCloudHousePrice($query);
                        if ($res['type'] != 'success') {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                        }

                        $insert['type'] = 1;
                        $insert['type_detail'] = $goods_transfers->type_detail;
                        $insert['warehouse_id'] = $goods_transfers->out_house;

                        $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->out_house]] - $v['receive_num'];
                        if($reduce_num<0){
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '库存不足--' . $v['custom_sku']];
                        }
                        $modify1Update[self::WAREHOUSE[$goods_transfers->out_house]] = $reduce_num;
                        $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);
                        $insert['shop_id'] = $goods_transfers->shop_id;
                        $insert['price'] = $query['price'];
                        $insert['now_inventory'] = $reduce_num;
                        $insert['now_total_price'] = $res['total_price'];
                        $insertIn = DB::table('cloudhouse_record')->insert($insert);
                        if (!$insertIn) {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增出库记录失败--' . $v['custom_sku']];
                        }
                        if(isset($factoryOut)){
                            $location_num = DB::table('cloudhouse_location_num')->where('custom_sku_id', $v['custom_sku_id'])->where('location_id',$factoryOut)
                                ->where('platform_id',$goods_transfers->platform_id)->select('id','num')->first();
                            if(!empty($location_num)){
                                $update_location = DB::table('cloudhouse_location_num')->where('id', $location_num->id)->update(['num'=>$location_num->num-$v['receive_num']]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位出库失败--' . $v['custom_sku']];
                                }
                            }else{
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '没有此库位库存--' . $v['custom_sku']];
                            }
                        }
                    } else {
//                        $query['warehouse_id'] = $goods_transfers->in_house;
//                        $query['custom_sku_id'] = $v['custom_sku_id'];
//                        $query['price'] = $this->GetCloudHousePrice($goods_transfers->in_house, $v['custom_sku_id']);
//                        $query['num'] = $v['receive_num'];
//                        $query['user_id'] = $user_id;
//                        $query['type'] = 2; //1为出2为入
//                        $res = $this->UpCloudHousePrice($query);
//                        if ($res['type'] != 'success') {
//                            db::rollback();// 回调
//                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
//                        }
//
                        $insert['type'] = 2;
//                        $insert['type_detail'] = $goods_transfers->type_detail;
                        $insert['warehouse_id'] = $goods_transfers->in_house;
//
//                        $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->in_house]] + $v['receive_num'];
//                        $modify1Update[self::WAREHOUSE[$goods_transfers->in_house]] = $reduce_num;
//                        $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);
//                        $insert['shop_id'] = $goods_transfers->shop_id;
//                        $insert['price'] = $query['price'];
//                        $insert['now_inventory'] = $reduce_num;
//                        $insert['now_total_price'] = $res['total_price'];
//                        $insertIn = DB::table('cloudhouse_record')->insert($insert);
//                        if (!$insertIn) {
//                            db::rollback();// 回调
//                            return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
//                        }

                    }
                } elseif ($goods_transfers->type == 4) {
                    //样品出入库
                    if ($goods_transfers->type_detail == 10) {
                        $query['warehouse_id'] = $goods_transfers->out_house;
                        $query['custom_sku_id'] = $v['custom_sku_id'];
                        $query['price'] = $this->GetCloudHousePrice($goods_transfers->out_house, $v['custom_sku_id']);
                        $query['num'] = $v['receive_num'];
                        $query['user_id'] = $user_id;
                        $query['type'] = 1; //1为出2为入
                        $res = $this->UpCloudHousePrice($query);
                        if ($res['type'] != 'success') {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                        }

                        $insert['type'] = 1;
                        $insert['type_detail'] = $goods_transfers->type_detail;
                        $insert['warehouse_id'] = $goods_transfers->out_house;

                        $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->out_house]] - $v['receive_num'];
                        if($reduce_num<0){
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '库存不足--' . $v['custom_sku']];
                        }
                        $modify1Update[self::WAREHOUSE[$goods_transfers->out_house]] = $reduce_num;
                        $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);

                        $insert['price'] = $query['price'];
                        $insert['now_inventory'] = $reduce_num;
                        $insert['now_total_price'] = $res['total_price'];
                        $insertOut = DB::table('cloudhouse_record')->insert($insert);
                        if (!$insertOut) {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增出库记录失败--' . $v['custom_sku']];
                        }

                        if(isset($factoryOut)){
                            $location_num = DB::table('cloudhouse_location_num')->where('custom_sku_id', $v['custom_sku_id'])->where('location_id',$factoryOut)
                                ->where('platform_id',$goods_transfers->platform_id)->select('id','num')->first();
                            if(!empty($location_num)){
                                $update_location = DB::table('cloudhouse_location_num')->where('id', $location_num->id)->update(['num'=>$location_num->num-$v['receive_num']]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位出库失败--' . $v['custom_sku']];
                                }
                            }else{
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '没有此库位库存--' . $v['custom_sku']];
                            }
                        }

                    } else {
//                        $query['warehouse_id'] = $goods_transfers->in_house;
//                        $query['custom_sku_id'] = $v['custom_sku_id'];
//                        $query['price'] = $this->GetCloudHousePrice($goods_transfers->in_house, $v['custom_sku_id']);
//                        $query['num'] = $v['receive_num'];
//                        $query['user_id'] = $user_id;
//                        $query['type'] = 2; //1为出2为入
//                        $res = $this->UpCloudHousePrice($query);
//                        if ($res['type'] != 'success') {
//                            db::rollback();// 回调
//                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
//                        }
//
                        $insert['type'] = 2;
//                        $insert['type_detail'] = $goods_transfers->type_detail;
                        $insert['warehouse_id'] = $goods_transfers->in_house;
//
//                        $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->in_house]] + $v['receive_num'];
//                        $modify1Update[self::WAREHOUSE[$goods_transfers->in_house]] = $reduce_num;
//                        $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);
//
//                        $insert['price'] = $query['price'];
//                        $insert['now_inventory'] = $reduce_num;
//                        $insert['now_total_price'] = $res['total_price'];
//                        $insertOut = DB::table('cloudhouse_record')->insert($insert);
//                        if (!$insertOut) {
//                            db::rollback();// 回调
//                            return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
//                        }

                        if(isset($factoryIn)){
                            $location_num = DB::table('cloudhouse_location_num')->where('custom_sku_id', $v['custom_sku_id'])->where('location_id',$factoryIn)
                                ->where('platform_id',$goods_transfers->platform_id)->select('id','num')->first();
                            if(!empty($location_num)){
                                $update_location = DB::table('cloudhouse_location_num')->where('id', $location_num->id)->update(['num'=>$location_num->num+$v['receive_num']]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位入库失败--' . $v['custom_sku']];
                                }
                            }else{
                                $insert_location = DB::table('cloudhouse_location_num')->insert([
                                    'custom_sku_id'=>$v['custom_sku_id'],
                                    'spu_id'=>$invenJson['spu_id'],
                                    'custom_sku'=>$invenJson['custom_sku'],
                                    'spu'=>$invenJson['spu'],
                                    'num'=>$v['receive_num'],
                                    'platform_id'=>$goods_transfers->platform_id,
                                    'location_id'=>$factoryIn,
                                    'create_time'=>time(),
                                ]);
                                if(!$insert_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位入库失败--' . $v['custom_sku']];
                                }
                            }
                        }
                    }
                } elseif ($goods_transfers->type == 6) {
                    //仓库调拨出入库
                    if($goods_transfers->type_detail==7){
                        $query['warehouse_id'] = $goods_transfers->out_house;
                        $query['custom_sku_id'] = $v['custom_sku_id'];
                        $query['price'] = $this->GetCloudHousePrice($goods_transfers->out_house, $v['custom_sku_id']);
                        $query['num'] = $v['receive_num'];
                        $query['user_id'] = $user_id;
                        $query['type'] = 1; //1为出2为入
                        $res = $this->UpCloudHousePrice($query);
                        if ($res['type'] != 'success') {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                        }

                        $insert['type'] = 1;
                        $insert['type_detail'] = $goods_transfers->type_detail;
                        $insert['warehouse_id'] = $goods_transfers->out_house;

                        $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->out_house]] - $v['receive_num'];
                        if($reduce_num<0){
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '库存不足--' . $v['custom_sku']];
                        }
                        $modify1Update[self::WAREHOUSE[$goods_transfers->out_house]] = $reduce_num;
                        $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);
                        $insert['price'] = $query['price'];
                        $insert['now_inventory'] = $reduce_num;
                        $insert['now_total_price'] = $res['total_price'];
                        $insertOut = DB::table('cloudhouse_record')->insert($insert);
                        if (!$insertOut) {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增出库记录失败--' . $v['custom_sku']];
                        }

                        if(isset($factoryOut)){
                            $location_num = DB::table('cloudhouse_location_num')->where('custom_sku_id', $v['custom_sku_id'])->where('location_id',$factoryOut)
                                ->where('platform_id',$goods_transfers->platform_id)->select('id','num')->first();
                            if(!empty($location_num)){
                                $update_location = DB::table('cloudhouse_location_num')->where('id', $location_num->id)->update(['num'=>$location_num->num-$v['receive_num']]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位出库失败--' . $v['custom_sku']];
                                }
                            }else{
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '没有此库位库存--' . $v['custom_sku']];
                            }
                        }
                    }

                    if($goods_transfers->type_detail==1){
//                        $query['warehouse_id'] = $goods_transfers->in_house;
//                        $query['custom_sku_id'] = $v['custom_sku_id'];
//                        $query['price'] = $this->GetCloudHousePrice($goods_transfers->in_house, $v['custom_sku_id']);
//                        $query['num'] = $v['receive_num'];
//                        $query['user_id'] = $user_id;
//                        $query['type'] = 2; //1为出2为入
//                        $res = $this->UpCloudHousePrice($query);
//                        if ($res['type'] != 'success') {
//                            db::rollback();// 回调
//                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
//                        }
//
                        $insert['type'] = 2;
//                        $insert['type_detail'] = $goods_transfers->type_detail;
                        $insert['warehouse_id'] = $goods_transfers->in_house;
//
//                        $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->in_house]] + $v['receive_num'];
//                        $modify1Update[self::WAREHOUSE[$goods_transfers->in_house]] = $reduce_num;
//                        $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);
//
//                        $insert['price'] = $query['price'];
//                        $insert['now_inventory'] = $reduce_num;
//                        $insert['now_total_price'] = $res['total_price'];
//                        $insertOut = DB::table('cloudhouse_record')->insert($insert);
//                        if (!$insertOut) {
//                            db::rollback();// 回调
//                            return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
//                        }
                        if(isset($factoryIn)){
                            $location_num = DB::table('cloudhouse_location_num')->where('custom_sku_id', $v['custom_sku_id'])->where('location_id',$factoryIn)
                                ->where('platform_id',$goods_transfers->platform_id)->select('id','num')->first();
                            if(!empty($location_num)){
                                $update_location = DB::table('cloudhouse_location_num')->where('id', $location_num->id)->update(['num'=>$location_num->num+$v['receive_num']]);
                                if(!$update_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位入库失败--' . $v['custom_sku']];
                                }
                            }else{
                                $insert_location = DB::table('cloudhouse_location_num')->insert([
                                    'custom_sku_id'=>$v['custom_sku_id'],
                                    'spu_id'=>$invenJson['spu_id'],
                                    'custom_sku'=>$invenJson['custom_sku'],
                                    'spu'=>$invenJson['spu'],
                                    'num'=>$v['receive_num'],
                                    'platform_id'=>$goods_transfers->platform_id,
                                    'location_id'=>$factoryIn,
                                    'create_time'=>time(),
                                ]);
                                if(!$insert_location){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '库位入库失败--' . $v['custom_sku']];
                                }
                            }
                        }
                    }

//                    }

                } elseif ($goods_transfers->type == 9) {
                      //组货出入库  17出 18入
                      if ($goods_transfers->type_detail == 17) {
                        $query['warehouse_id'] = $goods_transfers->out_house;
                        $query['custom_sku_id'] = $v['custom_sku_id'];
                        $query['price'] = $this->GetCloudHousePrice($goods_transfers->out_house, $v['custom_sku_id']);
                        $query['num'] = $v['receive_num'];
                        $query['user_id'] = $user_id;
                        $query['type'] = 1; //1为出2为入
                        $res = $this->UpCloudHousePrice($query);
                        if ($res['type'] != 'success') {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                        }

                        $insert['type'] = 1;
                        $insert['type_detail'] = $goods_transfers->type_detail;
                        $insert['warehouse_id'] = $goods_transfers->out_house;

                          $reduce_num = $invenJson[self::WAREHOUSE[$goods_transfers->out_house]] - $v['receive_num'];
                          if($reduce_num<0){
                              db::rollback();// 回调
                              return ['code' => 500, 'msg' => '库存不足--' . $v['custom_sku']];
                          }

                          $modify1Update[self::WAREHOUSE[$goods_transfers->out_house]] = $reduce_num;
                          $modify1 = DB::table('self_custom_sku')->where('id', $v['custom_sku_id'])->update($modify1Update);

                        $insert['shop_id'] = $goods_transfers->shop_id;
                        $insert['price'] = $query['price'];
                        $insert['now_inventory'] = $reduce_num;
                        $insert['now_total_price'] = $res['total_price'];
                        $insertIn = DB::table('cloudhouse_record')->insert($insert);
                        if (!$insertIn) {
                            db::rollback();// 回调
                            return ['code' => 500, 'msg' => '新增出库记录失败--' . $v['custom_sku']];
                        }


                        //生产组合入库
                        $group_custom_sku_id = $v['group_custom_sku_id'];
                        $group_cus[$group_custom_sku_id] =  $v;


                    }else{
                          $insert['type'] = 2;
                          $insert['warehouse_id'] = $goods_transfers->in_house;
                      }

                }
                $receive_total += $v['receive_num'];
            }else{
                continue;
            }

            if (isset($lxParams)) {
                $lxParams['wid']            = $insert['warehouse_id'];
                $lxParams['type']           = $insert['type'] == 1 ? 11 : 1;
                $lxParams['product_list'][] = [
                    'sku'      => $customSkuList[$insert['custom_sku_id']] ?? '',
                    'good_num' => $insert['num'],
                ];
            }

        }

        if(isset($change)){
            $change['user_id'] = $user_id;
            $change['warehouse_id'] = $goods_transfers->out_house;
            $change['type'] = 5;
            if($change['warehouse_id']==1){
                $change['location_code'] = 'M01-001';
            }else{
                $change['location_code'] = 'H01-001';
            }
            $change['order_no'] = $order_no;
            $this->location_change($change);
        }
        if(isset($change2)){
            $change2['user_id'] = $user_id;
            $change2['warehouse_id'] = $goods_transfers->out_house;
            $change2['type'] = 5;
            if($change2['warehouse_id']==1){
                $change2['location_code'] = 'M03-001';
            }else{
                $change2['location_code'] = 'H03-001';
            }

            $change2['order_no'] = $order_no;
            $this->location_change($change2);

        }
        if(isset($change3)){
            $change3['user_id'] = $user_id;
            $change3['warehouse_id'] = $goods_transfers->out_house;
            $change3['type'] = 5;
            if($change3['warehouse_id']==1){
                $change3['location_code'] = 'M04-001';
            }else{
                $change3['location_code'] = 'H04-001';
            }

            $change3['order_no'] = $order_no;
            $this->location_change($change3);
        }

        if($receive_total==0){
            db::rollback();// 回调
            return ['code'=>500,'msg'=>'接收数据不能为0'];
        }
        if($receive_total>$goods_transfers->total_num){
            db::rollback();// 回调
            return ['code'=>500,'msg'=>'接收数据不能大于清单数据'];
        }
        if(isset($on_shelf_num)){
            if($receive_total!=$on_shelf_num){
                db::rollback();// 回调
                return ['code'=>500,'msg'=>'下架数量与出库数量不一致，无法确认'];
            }
        }

        $updateTotal = DB::table('goods_transfers')->where('order_no',$order_no)->update(['unable_total_num'=>$unable_total,'usable_total_num'=>$usable_total,'receive_total_num'=>$receive_total,'sj_arrive_time'=>$date,'is_push'=>3,'confirm_id'=>$user_id]);
        if(!$updateTotal){
            db::rollback();// 回调
            return ['code'=>500,'msg'=>'修改接收总数失败'];
        }
        if($goods_transfers->back_order_no){
            //修改退回单的状态
            DB::table('goods_transfers')->where('order_no',$goods_transfers->back_order_no)->update(['back_order_no'=>$order_no,'is_push'=>5]);
        }
        $task = DB::table('tasks')->where('ext', 'like', "%{$order_no}%")->select('Id')->first();
        if(!empty($task)){
            $task_son = DB::table('tasks_son')->where('task_id', $task->Id)->select('Id')->first();
            $taskArr['Id'] = $task_son->Id;
            $taskArr['state'] = 3;
            $taskArr['feedback_type'] = 1;
            $call_task = new Task();
            $return = $call_task->task_son_complete($taskArr);
        }else{
            $return = 1;
        }

        if ($goods_transfers->type_detail == 17) {
            if(!empty($group_cus)){

                //如果是组合出库 则生产组合入库
                $OutInRes = $this->ConfirmGroupOutInByOrderNo($order_no);
            //    $OutInRes =  $this->ConfirmGroupOutIn($goods_transfers,$group_cus);
               if($OutInRes['type']=='fail'){
                    db::rollback();// 回调
                    return ['code'=>500,'msg'=>$OutInRes['msg']];
               }
            }
        }


        //同步库存到领星
        if (isset($lxParams)) {
            $data = [
                'fun'    => $lxParams['type'] == 1 ? 'addInStorageOrder' : 'addOutStorageOrder',
                'params' => $lxParams,
            ];

            //加入同步库存到翎星队列
            $job = new LingXingJob($data);
            $job->dispatch($data)->onQueue('ling_xing');
        }

        db::commit();
        if($return!=1){
            return ['code'=>200,'msg'=>'确认成功，但此任务自动完成失败,请手动去我的任务完成'];
        }
        return ['code'=>200,'msg'=>'确认成功'];
    }


    //生成组货入库
    public function ConfirmGroupOutInByOrderNo($order_no){


        $task = db::table('goods_transfers')->where('order_no',$order_no)->first();

        $list = db::table('goods_transfers_detail')->where('order_no',$order_no)->get();

        $goods_transfers_arr['order_no'] =  rand(100,999).time();
        $box_id = $this->Addbox2( $goods_transfers_arr['order_no'],$task->out_house);

        $sku_count = [];
        $box_num = 0;
        $newdata = [];
        foreach ($list as $v) {
            # code...
            $sku_count[$v->group_custom_sku_id] = 1;
            $newdata[$v->group_custom_sku_id]['custom_sku'] = $v->group_custom_sku;
            $newdata[$v->group_custom_sku_id]['custom_sku_id'] = $v->group_custom_sku_id;

            $spus = db::table('self_custom_sku')->where('id',$v->group_custom_sku_id)->first();

            $newdata[$v->group_custom_sku_id]['transfers_num'] = $v->transfers_num;
            $newdata[$v->group_custom_sku_id]['spu'] = $spus->spu;
            $newdata[$v->group_custom_sku_id]['spu_id'] = $spus->spu_id;

            $newdata[$v->group_custom_sku_id]['order_no'] =  $goods_transfers_arr['order_no'];
            $newdata[$v->group_custom_sku_id]['box_id'] = $box_id;
            $newdata[$v->group_custom_sku_id]['createtime'] = date('Y-m-d H:i:s',time());

        }

        foreach ($newdata as $ndv) {
            # code...
            $box_num+=$ndv['transfers_num'];
        }


        $goods_transfers_arr['type_detail'] = 18;

        $goods_transfers_arr['in_house'] =  $task->out_house;
        $goods_transfers_arr['out_house'] = 0;
        $goods_transfers_arr['is_push'] =2;
        $goods_transfers_arr['status'] =3;
        $goods_transfers_arr['sku_count'] =count($sku_count);
        $goods_transfers_arr['total_num'] =$box_num;
        $goods_transfers_arr['user_id'] =$task->user_id;
        $goods_transfers_arr['createtime'] = date('Y-m-d H:i:s',time());
        $goods_transfers_arr['yj_arrive_time'] = $task->yj_arrive_time;
        $goods_transfers_arr['type'] =9;
        $goods_transfers_arr['shop_id'] =$task->shop_id;
        $goods_transfers_arr['platform_id'] =$task->platform_id;
        
        try {
            //code...
            $transfers_id = DB::table('goods_transfers')->insertGetId($goods_transfers_arr);
        } catch (\Throwable $th) {
            //throw $th;
            return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
        }

   
        

        //插入 goods_transfer_box
        $goods_transfer_box_i['order_no'] =$goods_transfers_arr['order_no'];
        $goods_transfer_box_i['box_num'] =$box_num;
        try {
            db::table('goods_transfers_box')->where('id',$box_id)->update($goods_transfer_box_i);
        } catch (\Throwable $th) {
        //throw $th;
            return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
        }




        //插入goods_transfers_detail
        foreach ($newdata as $nv) {

            try {
                db::table('goods_transfers_detail')->insert($nv);
            } catch (\Throwable $th) {
            //throw $th;
                return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
            }
         
            
      
    

            //插入goods_transfer_box_detail
            $box_detail_i['box_id'] = $box_id;
            $box_detail_i['custom_sku'] = $nv['custom_sku'];
            $box_detail_i['custom_sku_id'] = $nv['custom_sku_id'];
            $box_detail_i['box_num'] = $nv['transfers_num'];
            try {
                db::table('goods_transfers_box_detail')->insert($box_detail_i);
            } catch (\Throwable $th) {
                //throw $th;
                return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
            }

            
        }

        

        // db::rollback();// 回调
        $rdata['goods_transfers_arr'] = $goods_transfers_arr;
        $rdata['goods_transfer_box_i'] = $goods_transfer_box_i;
        $rdata['box_detail_i'] = $box_detail_i;
        $rdata['detail_i'] = $newdata;
        return['type'=>'success','msg'=>'成功','data'=> $rdata];
        // var_dump($rdata);
        // exit;

    }



    //生成组货入库
    public function ConfirmGroupOutIn($goods_transfers,$group_cus){


        $box_num = 0;
        foreach ($group_cus as $v) {
            $box_num+=$v['receive_num'];
        }

        $goods_transfers_arr = json_decode(json_encode($goods_transfers),true);
       
        //组合出库成功新增入库记录

        //插入goods_transfers
        $box_num = 0;
        $sku_count = 0;
        foreach ($group_cus as $v) {
            $box_num+=$v['receive_num'];
            $sku_count++;
        }
        unset($goods_transfers_arr['id']);
        $goods_transfers_arr['order_no'] =  rand(100,999).time();
        $goods_transfers_arr['type_detail'] = 18;
        $out_house_group = $goods_transfers_arr['out_house'];
        $goods_transfers_arr['in_house'] =  $out_house_group;
        $goods_transfers_arr['out_house'] = 0;
        $goods_transfers_arr['is_push'] =2;
        $goods_transfers_arr['status'] =3;
        $goods_transfers_arr['sku_count'] =$sku_count;
        $goods_transfers_arr['total_num'] =$box_num;
        try {
            //code...
            $transfers_id = DB::table('goods_transfers')->insertGetId($goods_transfers_arr);
        } catch (\Throwable $th) {
            //throw $th;
            return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
        }

        $box_id = $this->Addbox2( $goods_transfers_arr['order_no'],$out_house_group);
        

        //插入 goods_transfer_box
        $goods_transfer_box_i['order_no'] =$goods_transfers_arr['order_no'];
        $goods_transfer_box_i['box_num'] =$box_num;
        try {
            db::table('goods_transfers_box')->where('id',$box_id)->update($goods_transfer_box_i);
        } catch (\Throwable $th) {
        //throw $th;
            return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
        }




        //插入goods_transfers_detail
        foreach ($group_cus as $v) {
            # code...
            //插入goods_transfer_detail
            $group_custom_sku_id = $v['group_custom_sku_id'];
            $groupcus = db::table('self_custom_sku')->where('id',$group_custom_sku_id)->first();
            $groupspu = '';
            $groupspu_id = 0;

            if($groupcus){
                $groupspu = $groupcus->spu;
                $groupspu_id =  $groupcus->spu_id;
            }

            $detail_i['order_no'] = $goods_transfers_arr['order_no'];
            $detail_i['spu'] =$groupspu;
            $detail_i['spu_id'] =$groupspu_id;
            $detail_i['custom_sku'] = $groupcus->custom_sku;
            $detail_i['transfers_num'] =$v['receive_num'];
            $detail_i['createtime'] = date('Y-m-d H:i:s',time());
            $detail_i['box_id'] =  $box_id;
            $detail_i['order_no'] = $goods_transfers_arr['order_no'];
            $detail_i['custom_sku_id'] =  $group_custom_sku_id;
            try {
                db::table('goods_transfers_detail')->insert($detail_i);
            } catch (\Throwable $th) {
            //throw $th;
                return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
            }
    

            //插入goods_transfer_box_detail
            $box_detail_i['box_id'] = $box_id;
            $box_detail_i['custom_sku'] = $groupcus->custom_sku;
            $box_detail_i['custom_sku_id'] = $group_custom_sku_id;
            $box_detail_i['box_num'] = $v['receive_num'];
            try {
                db::table('goods_transfers_box_detail')->insert($box_detail_i);
            } catch (\Throwable $th) {
                //throw $th;
                return['type'=>'fail','msg'=>$th->getFile().'-'.$th->getLine().'-'.$th->getMessage()];
            }

            
        }

        

        // db::rollback();// 回调
        $rdata['goods_transfers_arr'] = $goods_transfers_arr;
        $rdata['goods_transfer_box_i'] = $goods_transfer_box_i;
        $rdata['box_detail_i'] = $box_detail_i;
        $rdata['detail_i'] = $detail_i;
        return['type'=>'success','msg'=>'成功','data'=> $rdata];
        // var_dump($rdata);
        // exit;

    }
    /**
     * @Desc:采购详情导出
     * @param $params
     * @return true
     * @throws \Exception
     * @author: Liu Sinian
     * @Time: 2023/2/23 16:39
     */
    public function exportTransferDataDetail($params)
    {
        if (isset($params['order_no']) && !empty($params['order_no'])){
            $order = db::table('goods_transfers')->where('order_no', $params['order_no'])->first();
            $params['find_user_id'] = $params['export_user_id'];
            $params['posttype'] = 2;
            $params['type_detail'] = $order->type_detail;
            $result = $this->transfers_data_detail($params);

            return $result;
            $list = $this->goodTransfersDetailModel::query()->where('order_no',$params['order_no'])->select()->get()->toArray();
            if (!empty($list)){
                $imgList = [];
                foreach ($list as &$item){
                    // 获取库存sku详情
                    $customSkuData = BaseModel::GetCustomSkus($item['custom_sku']);
                    // 获取颜色
                    $color = BaseModel::GetColorSize($customSkuData['color_id']);
                    $item['color'] = $color['name'].'/'.$color['identifying']; // 颜色
                    $item['size'] = $customSkuData['size']; // 尺寸
                    $customSku = $customSkuData['custom_sku'];
                    if ($customSkuData['old_custom_sku']){
                        $customSku = $customSkuData['old_custom_sku'];
                    }
                    $img =  $this->GetCustomskuImg($customSku); // 图片
                    if (!in_array($img, $imgList)){
                        $imgList[] = $img;
                        $item['img'] = $img;
                    }else{
                        $item['img'] = "";
                    }
                }
            }else{
                throw new \Exception('导出数据为空！');
            }
            // excel文件表头
            $excelName = '采购详情'.time();
            // 表头
            $excelTitle = [
                'contract_no' => 'contract_no',
                'custom_sku' => '库存sku',
                'img' => '图片',
                'spu' => 'SPU',
                'color' => '颜色',
                'size' => '尺码',
                'transfers_num' => '采购数量',
                'receive_num' => '实际接收数量',
                'createtime' => '创建时间'
            ];
            if (isset($params['not_img']) && $params['not_img'] == 1){
                $excelName = '采购详情(无图片)'.time();
                $excelTitle = [
                    'contract_no' => 'contract_no',
                    'custom_sku' => '库存sku',
                    'spu' => 'SPU',
                    'color' => '颜色',
                    'size' => '尺码',
                    'transfers_num' => '采购数量',
                    'receive_num' => '实际接收数量',
                    'createtime' => '创建时间'
                ];
            }
            // 组织导出列表数据
            $excelData = [
                'data' => $list,
                'title_list' => $excelTitle,
                'title' => $excelName,
                'type' => '采购详情导出',
                'user_id' => $params['export_user_id']
            ];

        }else{
            throw new \Exception('未给定采购号');
        }

        return $excelData;
    }


    /**
     * @Desc: //修改待推送库存变动数据
     * @param $params
     * @return ['code'=>'','msg=>'']
     * @author: 严威
     * @Time: 2023/4/7 16:37
     * @updateTime: 2023/4/7 16:37
     */
    public function update_goods_transfers($params){
        $order_no =  isset($params['order_no'])?$params['order_no']:0;

        if($order_no!=0){
            if(is_array($params['data'])){
                $sku_count = 0;
                $total_num = 0;
                foreach ($params['data'] as $v){
                    if($v['transfers_num']==0){
                        DB::table('goods_transfers_detail')->where('order_no',$order_no)->where('custom_sku_id',$v['custom_sku_id'])->delete();
                    }else{
                        $sku_count++;
                    }
                    DB::table('goods_transfers_detail')->where('order_no',$order_no)->where('custom_sku_id',$v['custom_sku_id'])->update(['transfers_num'=>$v['transfers_num']]);
                    $total_num += $v['transfers_num'];
                }
                DB::table('goods_transfers')->where('order_no',$params['order_no'])->update(['total_num'=>$total_num,'sku_count'=>$sku_count]);
                return ['code'=>200,'msg'=>'修改成功'];
            }else{
                return ['code'=>500,'msg'=>'数据错误'];
            }
        }else{
            return ['code'=>500,'msg'=>'未获取到批号'];
        }
    }


    //生成中转箱码
    public function create_transfer_box($params){
        if(!isset($params['order_no'])){
            return ['code'=>500,'msg'=>'未获取到批号'];
        }else{
            $order_no = $params['order_no'];
            $goods_transfers = DB::table('goods_transfers')->where('order_no',$order_no)->select('in_house')->first();
        }
//        $remarks = isset($params['remarks']) ? $params['remarks'] : '';
        $num = $params['num']??1;

        db::beginTransaction();    //开启事务

        for ($i=0; $i < $num; $i++) {
            # code...
            $thisId = DB::table('goods_transfers_box')->insertGetId(['order_no'=>$order_no,'warehouse_id'=>$goods_transfers->in_house,'type'=>1]);
            if($thisId){
                $box_code = 'bc'.$thisId;
                $update = DB::table('goods_transfers_box')->where('id',$thisId)->update(['box_code'=>$box_code]);
                if(!$update){
                    db::rollback();// 回调
                    return ['code'=>500,'msg'=>'新增中装箱失败'];
                }

            }else{
                db::rollback();// 回调
                return ['code'=>500,'msg'=>'新增中装箱失败'];
            }
            $i++;
        }

        db::commit();
        return ['code'=>200,'msg'=>'新增成功'];
    }


    public function delete_transfer_box($params){
        $id = $params['id'];
        $detail = DB::table('goods_transfers_box_detail')->where('box_id',$id)->get();
        if($detail->isEmpty()){
            DB::table('goods_transfers_box')->where('id',$id)->delete();
            DB::table('goods_transfers_box_detail')->where('box_id',$id)->delete();
            return ['code'=>200,'msg'=>'删除成功'];
        }else{
            return ['code'=>200,'msg'=>'删除失败，不能删除已有数据的中转箱'];
        }

    }

    //批次中转箱列表
    public function transfers_box_list($params){

        $order_no =  isset($params['order_no'])?$params['order_no']:0;

        $list = DB::table('goods_transfers_box')->where('order_no',$order_no)->where('is_delete',0)->select('id','box_code','box_num','onshelf_num')->get()->toArray();

        foreach ($list as $v){
            if(strstr($v->box_code,'box')){
                $v->type = '下架';
            }
            if(strstr($v->box_code,'bc')){
                $v->type = '上架';
            }
        }

        return $list;
    }

    //新增中转箱货物信息
    public function update_transfers_box($params){
        if(isset($params['id'])){
            $id = $params['id'];
            $box = DB::table('goods_transfers_box')->where('id',$id)->select('order_no')->first();
            if(empty($box)){
                return ['code'=>500,'msg'=>'没有此中转任务id'];
            }
            $boxData = DB::table('goods_transfers_box')->where('order_no',$box->order_no)->select('id')->get();
            $boxData =json_decode(json_encode($boxData),true);
            $boxIds = array_column($boxData,'id');
        }

        if(isset($params['box_code'])){
            $box = DB::table('goods_transfers_box')->where('box_code',$params['box_code'])->select('order_no','id')->first();
            $id = $box->id;
            if(empty($box)){
                return ['code'=>500,'msg'=>'没有此中转箱'];
            }
            $boxIds[0] = $box->id;
        }

        $boxDetail_data = DB::table('goods_transfers_box_detail')->whereIn('box_id',$boxIds)->get();
        $boxCustom = array();
        $boxArr = array();

        foreach ($boxDetail_data as $b){
            if(isset($boxCustom[$b->custom_sku_id])){
                $boxCustom[$b->custom_sku_id] += $b->box_num;
            }else{
                $boxCustom[$b->custom_sku_id] = $b->box_num;
            }
            $boxArr[$b->box_id][$b->custom_sku_id] = $b->box_num;
        }

        if(is_array($params['data'])){
            db::beginTransaction();    //开启事务
            $num = 0;
            foreach ($params['data'] as $v){
                $insert['custom_sku_id'] = $this->GetCustomSkuId($v['custom_sku']);

                $transfers_detail = DB::table('goods_transfers_detail')->where('order_no',$box->order_no)->where('custom_sku_id',$insert['custom_sku_id'])->select('id','transfers_num')->get();
                if($transfers_detail->isEmpty()){
                    return ['code'=>500,'msg'=>'清单中没有此'.$v['custom_sku'].'，无法添加到中转任务'];
                }else{
                    $transfers_detail_num = 0;
                    foreach ($transfers_detail as $t){
                        $transfers_detail_num += $t->transfers_num;
                    }
                }
                if(isset($boxCustom[$insert['custom_sku_id']])){
                    $box_total_receive = $boxCustom[$insert['custom_sku_id']]+$v['box_num'];
                }else{
                    $box_total_receive = $v['box_num'];
                }
                if($box_total_receive>$transfers_detail_num){
                    $exceed = $box_total_receive-$transfers_detail_num;
                    return ['code'=>500,'msg'=>$v['custom_sku'].'收货数量超出清单数量'.$exceed.'个，无法录入'];
                }
                if(isset($boxArr[$id][$insert['custom_sku_id']])){
                    $update = DB::table('goods_transfers_box_detail')->where('box_id',$id)->where('custom_sku_id',$insert['custom_sku_id'])->update(['box_num'=>$v['box_num']+$boxArr[$id][$insert['custom_sku_id']]]);
                    $num+=$v['box_num'];
                }else{
                    $insert['box_id'] = $id;
                    $insert['box_num'] = $v['box_num'];
                    $insert['custom_sku'] = $v['custom_sku'];
                    $add = DB::table('goods_transfers_box_detail')->insert($insert);
                    if(!$add){
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'新增货物数据失败'];
                    }else{
                        $num+=$v['box_num'];
                    }
                }

            }
            $box_data = DB::table('goods_transfers_box')->where('id',$id)->select('box_num')->first();
            if(!empty($box_data)){
                DB::table('goods_transfers_box')->where('id',$id)->update(['box_num'=>$num+$box_data->box_num]);
            }else{
                DB::table('goods_transfers_box')->where('id',$id)->update(['box_num'=>$num]);
            }

            db::commit();
            return ['code'=>200,'msg'=>'收货成功'];
        }else{
            return ['code'=>500,'msg'=>'数据错误'];
        }

    }


    //未分配列表
    public function GetTransfersDetailList($params){

        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = db::table('goods_transfers_box_detail as a')->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')->leftjoin('goods_transfers as c','c.order_no','=','b.order_no')->where('a.is_plan',0)->groupby('b.order_no','a.custom_sku_id')->select(DB::raw('sum(a.shelf_num) as shelf_num'),DB::raw('sum(a.box_num) as box_num'),'custom_sku','b.order_no','a.custom_sku_id','c.contract_no');

        $totalNum = $list->get()->count();
        

        $list = $list ->offset($pagenNum)->limit($limit)->get();

        foreach ($list as $v) {
            # code...

            $v->dec_num = $v->box_num - $v->shelf_num;
            $v->contract_no = json_decode($v->contract_no)[0];
            $ratio =  db::table('cloudhouse_custom_sku')->where('contract_no',$v->contract_no)->first();
            if(!$ratio){
                $v->ratio = [];
            }else{
                $ratios = json_decode($ratio->ratio,true);
                $ratioss = [];
                if(!is_array($ratios)){
                    $v->ratio = [];
                }else{
                    foreach ($ratios as $rk => $rv) {
                        # code...
                        $ratioone['platform_id'] = $rk;
                        $ratioone['num'] = $rv;
                        $ratioss[] = $ratioone;
                    }
                    $v->ratio = $ratioss;
                }

            }


        }


        return ['type'=>'success','data'=>$list,'total_num'=>$totalNum];
    }



    //设置入库分配额
    public function SetTransfersPlan($params){

        $i['user_id'] = $params['user_id']??1;
        $i['box_code'] = $params['box_code']??1;
        $i['custom_sku_id'] = $params['custom_sku_id']??1;
        $i['create_time'] = date('Y-m-d H:i:s',time());
        $i['num'] = 0;
        $i['plan_num'] = $params['plan_num']??1;
        $i['platform_id'] = $params['platform_id']??1;
        db::table('goods_transfers_plan')->insert($i);
        db::table('goods_transfers_box_detail as a')->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')->where('b.box_code',$i['box_code'])->where('a.custom_sku_id',$i['custom_sku_id'])->update(['is_plan'=>1]);
        return ['type'=>'success','msg'=>'成功'];
    }


    //获取比例
    public function GetProportion($params){

        $list =  db::table('cloudhouse_custom_sku')->where('contract_no',$params['contract_no']);
        // if(isset($params['custom_sku_id'])){
        //     $list = $list->where('custom_sku_id',$params['custom_sku_id']);
        // }
        $list = $list->first();

        if(!$list){
            return['type'=>'fail','msg'=>'该合同未分配比例'];
        }
        $ratio = json_decode($list->ratio,true);
        $ratios = [];
        foreach ($ratio as $key => $value) {
            # code...
            $ratioone['platform_id'] = $key;
            $ratioone['num'] = $value;
            $ratios[] = $ratioone;
        }

        return ['type'=>'success','data'=>$ratios];
    }




    //显示中转箱数据明细
    public function transfers_box_detail($params){
        if(!isset($params['id'])){
            return ['code'=>500,'msg'=>'未获取到中转箱id'];
        }else{
            $id = $params['id'];
        }
        $detail = DB::table('goods_transfers_box_detail')->where('box_id',$id)->get();
        if(!empty($detail)){
            foreach ($detail as $k=>$v){
                $detail[$k]->img = $this->GetCustomskuImg($v->custom_sku);
                $detail[$k]->location_code = $this->Getlocation($v->location_ids)?$this->Getlocation($v->location_ids)['location_code']:'';
                $order_no =  DB::table('goods_transfers_box')->where('id',$v->box_id)->first();
                $ratio = db::table('goods_transfers_detail')->where('order_no',$order_no->order_no)->where('custom_sku_id',$v->custom_sku_id)->first();
    
                $ratios = [];
                if($ratio){
                    $ratio_detail = json_decode($ratio->ratio_detail,true);
                    if(is_array($ratio_detail)){
                        foreach ($ratio_detail as $rp => $rv) {
                            # code...
                            $r_one['platform'] = db::table('platform')->where('Id',$rp)->first()->name;
                            $r_one['platform_id'] = $rp;
                            $r_one['num'] =$rv;
                            $ratios[] = $r_one;
                        }
                    }
 
                }
                $v->ratio = $ratios;
            }
        }
        return $detail;
    }

    public function GetLocationInfo($params){
        $custom_sku_id = $params['custom_sku_id'];
        $res = $this->GetCustomSkuIventoryByLocationCodeInfo($custom_sku_id);
        return ['type'=>'success','data'=>$res];
    }

    public function get_push_info($params){
        $custom_sku_id = $params['custom_sku_id'];
        $warehouse_id = $params['warehouse_id'];
        $data = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->where('a.out_house',$warehouse_id)
            ->where('b.custom_sku_id',$custom_sku_id)
            ->whereIn('a.type_detail',$this->GetFieldTypeDetail())
            ->whereIn('is_push',[1,2,4])
            ->select('a.order_no','a.platform_id','a.user_id','a.type_detail','b.transfers_num')
            ->get()->toArray();
        if(!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]->user = $this->GetUsers($v->user_id)['account']??'';
                $data[$k]->platform = $this->GetPlatform($v->platform_id)['name']??'';
                $data[$k]->type_detail_name = self::TYPE_DETAIL[$v->type_detail];
            }

        }
        return ['type'=>'success','data'=>$data];
    }


    public function GetCusByBoxCode($params){
        $custom_sku = $params['custom_sku'];
        $box_data = db::table('self_custom_sku')->where('custom_sku',$custom_sku)->orwhere('old_custom_sku',$custom_sku)->select('id','box_num')->first();

        if(!$box_data){
            return ['type'=>'fail','msg'=>'无此商品'];
        }
        $data['custom_sku'] =  $custom_sku;
        $data['id'] = $box_data->id;
        $data['num'] =   $box_data->box_num;
        $data['img'] =   $this->GetCustomskuImg($custom_sku);

        // foreach ($box_data as $v) {
        //     # code...
        //     $data_one['num'] = $v->box_num;
        //     $data_one['custom_sku'] = $v->custom_sku;
        //     $data_one['id'] = $v->id;
        //     // $data_one['box_code'] = $box_code;
        //     $data_one['img'] =
        //     // $data_one['contract_no'] = db::table('goods_transfers_detail')->where('order_no',$v->order_no)->first()->contract_no??'';
        //     $data[] = $data_one;
        // }


        return ['type'=>'success','data'=>$data];

    }
    //库位上下架商品库存
    public function location_changeb($params){
        $user_id = 0;
        if(isset($params['user_id'])){
            $user_id= $params['user_id'];
        }else{
            $user_data = DB::table('users')->where('token', '=', $params['token'])->select('Id', 'account')->first();
            if(empty($user_data)){
                return ['code'=>500,'msg'=>'该账号异常，无法操作'];
            }
            $user_id = $user_data->Id;
        }


        $day = date('Y-m-d',time());
        $order_nums = db::table('goods_transfers')->where('ds',$day)->orderby('ds_num','desc')->first();

        if($order_nums){
            $order_num = $order_nums->order_num+1;
        }else{
            $order_num = 1;
        }
        $order_no = date('Ymd').str_pad($order_num, 3, 0, STR_PAD_LEFT);


        if(isset($params['warehouse_id'])){
            $warehouse_id = $params['warehouse_id'];
        }else{
            return ['code'=>500,'msg'=>'未获取到仓库id'];
        }

        $location_code = 'A01-001';




        $goods_transfers =  DB::table('goods_transfers')->where('order_no',$order_no)->select('in_house','out_house','id','is_push','type_detail','status','platform_id','shop_id')->first();
        if(!isset($params['platform_id'])){
            return ['code'=>500,'msg'=>'请选择国家'];
        }
        $platform_id = $params['platform_id'];



        $newdata = [];

        foreach ($params['data'] as $v){
            $newdata[$v['id']]['custom_sku'] = $v['custom_sku'];
            $newdata[$v['id']]['id'] = $v['id'];
            $newdata[$v['id']]['spu'] = $v['spu'];
            if(isset( $newdata[$v['id']]['num'])){
                $newdata[$v['id']]['num'] += $v['num'];
            }else{
                $newdata[$v['id']]['num'] = $v['num'];
            }
        }
   

        // 上架：1，下架：2，调整上架：3，验货上架：5
        $checkType = [1, 2, 3];
        if (in_array($type, $checkType)){
            $type_detail = $goods_transfers->type_detail;
            $taskClassMdl = db::table('task_class')
                ->whereIn('fid', [42, 43, 44, 80])
                ->get();
            $taskClassMdl = json_decode(json_encode($taskClassMdl),true); 
            $taskClassIds = array_column($taskClassMdl, 'id');
            $tasks = DB::table('tasks')
                ->where('ext', 'like', "%{$order_no}%")
                ->where('is_deleted', 0)
                ->whereIn('class_id', $taskClassIds)
                ->select('desc','Id','class_id','ext')
                ->first();
            if(!empty($tasks)){
                if($goods_transfers->status<3){
                    return ['code'=>500,'msg'=>'该任务未审核通过，无法操作'];
                }
                if($tasks->Id==4){
                    if($type==1||$type==2){
                        return ['code'=>500,'msg'=>'该任务未已被拒绝，无法继续操作'];
                    }
                }
                $task_son = DB::table('tasks_son')->where('task_id', $tasks->Id)->select('state','Id','tasks_node_id')->first();
                if(!$task_son){
                    return ['code'=>500,'msg'=>'无此任务子节点'.$tasks->Id];
                }
                if($task_son->state==1){
                    $taskParam['Id'] = $task_son->Id;
                    $taskParam['tasks_node_id'] = $task_son->tasks_node_id;
                    $taskParam['task_id'] = $tasks->Id;
                    $taskParam['user_id'] = $user_id;
                    $taskModel = new Task();
                    $result = $taskModel->task_accept_model($taskParam);
                }

            }
            if($goods_transfers->is_push==3){
                return ['code'=>500,'msg'=>'订单已完成，无法继续操作'];
            }
            if($type!=3){
                if($goods_transfers->is_push==2){
                    //修改订单状态为操作中
                    $update =  DB::table('goods_transfers')->where('id',$goods_transfers->id)->update(['is_push'=>4]);
                    if(!$update){
                        return ['code'=>500,'msg'=>'修改状态失败'];
                    }
                }
                if($type==1){
                    if($type_detail==16){
                        if($warehouse_id!=$goods_transfers->out_house){
                            return ['code'=>500,'msg'=>'仓库选择错误'];
                        }
                    }else{
                        if($warehouse_id!=$goods_transfers->in_house){
                            return ['code'=>500,'msg'=>'仓库选择错误'];
                        }
                    }
                }elseif($type==2){
                    if($warehouse_id!=$goods_transfers->out_house){
                        return ['code'=>500,'msg'=>'仓库选择错误'];
                    }
                }
            }


        }

        $location = DB::table('cloudhouse_warehouse_location')->where('location_code',$location_code)->where('warehouse_id',$warehouse_id)->select('id','level')->first();
        if(!empty($location)){
            if($location->level!=3){
                return ['code'=>500,'msg'=>'此库位非三级库位，无法操作'];
            }else{
                $location_id = $location->id;
            }
        }else{
            return ['code'=>500,'msg'=>'没有此库位，请核对库位编码是否正确'];
        }

        $location_data = DB::table('cloudhouse_location_num')->where('location_id',$location_id)->select('custom_sku_id',
        'num','lock_num','platform_id')->get();

        $locationArr = array();
        $locationAll = array();

        if(!$location_data->isEmpty()){
            foreach ($location_data as $d){
                if(isset($locationAll[$d->custom_sku_id])){
                    $locationAll[$d->custom_sku_id] += $d->num;
                }else{
                    $locationAll[$d->custom_sku_id] = $d->num;
                }

                if($d->platform_id == $platform_id){
                    $locationArr[$d->custom_sku_id] = $d->num;
                }
            }
        }

        if($type==1){
            $custom_skuArr = array_column($params['data'],'id');
            $goods_transfers_detail = DB::table('goods_transfers_detail')->where('order_no',$order_no)->whereIn('custom_sku_id',$custom_skuArr)
                ->select('id','contract_no','custom_sku_id','receive_num','transfers_num')->get()->toArray();
            $contractArr = [];
            $transfersDetail = [];
            if(!empty($goods_transfers_detail)){
                foreach ($goods_transfers_detail as $gd){
                    if($gd->contract_no){
                        $contractArr[$gd->custom_sku_id] = $gd->contract_no;
                    }
                    $transfersDetail[$gd->custom_sku_id] = $gd;
                }
            }
            $inventoryArr = [];
            $self_custom_sku = DB::table('self_custom_sku')->whereIn('id',$custom_skuArr)->get()->toArray();
            if(!empty($self_custom_sku)){
                $self_custom_sku = json_decode(json_encode($self_custom_sku),true);
                foreach ($self_custom_sku as $sf){
                    $inventoryArr[$sf['id']] = $sf;
                }
            }
        }


        db::beginTransaction();
        try {
            $box_total = 0;
            $box_total2 = 0;
            foreach ($params['data'] as $v){
                // if($type==1){
                //     //如果是采购入库  则根据计划分配上架
                //     $plans = db::table('goods_transfers_plan')->where('box_code',$params['task_code'])->where('custom_sku_id',$v['id'])->get();
                //     $platform_id = 0;
                //     $goods_transfers_plan_id = 0;
                //     $goods_transfers_plan_num = 0;
                //     foreach ($plans as $v) {
                //         # code...
                //         if($platform_id==0){
                //             if(($v->plan_num - $v->num)>0){
                //                 $platform_id = $v->platform_id;
                //                 $goods_transfers_plan_id = $v->id;
                //                 $goods_transfers_plan_num = $v->num;
                //             }
                //         }

                //     }
                //     if($platform_id==0){
                //         return ['code'=>500,'msg'=>'预分配数量不足'];
                //     }
                //     //修改预分配
                //     db::table('goods_transfers_plan')->where('id',$goods_transfers_plan_id)->update(['num'=>$goods_transfers_plan_num]);
                // }
                $time = date('Y-m-d H:i:s');
                if($v['num']<1){
                    continue;
                }else{
                    if($type == 5){
                        $log['remark'] = '验货上架';
                    }elseif($type == 6){
                        $log['remark'] = '验货下架';
                    }else{
                        if($type == 3){
                            $log['remark'] = '调整上架';
                        }
                        $boxDetail = DB::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id']);
                        if($type==3){
                            $boxDetail = $boxDetail->select('box_num','shelf_num','id','location_ids')->get()->toArray();
                        }elseif($type==2){
                            $boxDetail = $boxDetail->where('location_ids',$location_id)->select('box_num','shelf_num','id','location_ids')->first();
                        }else{
                            $boxDetail = $boxDetail->select('box_num','shelf_num','id','location_ids')->first();
                        }

                        if(!empty($boxDetail)){
                            if($type==2) {
                                $shelf_num = $boxDetail->shelf_num;
                                if ($v['num']+$boxDetail->shelf_num > $boxDetail->box_num) {
                                    $exceed = $v['num'] - $boxDetail->box_num;
                                    throw new \Exception('操作失败，' . $v['custom_sku'] . '超出任务数量' . $exceed . '件');
                                }
                            }elseif($type==3) {
                                $shelf_num = 0;
                                $shelf_numArr = [];
                                foreach ($boxDetail as $bd){
                                    if($bd->shelf_num>0){
                                        $shelf_numArr[] = ['location_id'=>$bd->location_ids,'shelf_num'=>$bd->shelf_num];
                                    }
                                    $shelf_num += $bd->shelf_num;
                                }
                                $shelf_balance_num = $shelf_num - $v['num'];
                                if($shelf_balance_num<0){
                                    throw new \Exception('操作失败，'.$v['custom_sku'].'调整上架数量: '.$v['num'].' 大于已下架数量：'.$shelf_num);
                                }
                            }else{
                                $shelf_num = $boxDetail->shelf_num;
                                if ($v['num']+$shelf_num > $boxDetail->box_num) {
                                    $exceed = $v['num'] +$shelf_num - $boxDetail->box_num;
                                    throw new \Exception('操作失败，' . $v['custom_sku'] . '超出任务数量' . $exceed . '件');
                                }
                            }
                        }else{
                            throw new \Exception('操作失败，'.$box_id.'任务中没有'.$v['custom_sku'].'，请检查库位和箱码是否正确');
                        }
                    }

                    $log['spu'] = $v['spu'];
                    $log['spu_id'] = $this->GetSpuId($v['spu']);
                    $log['custom_sku_id'] = $v['id'];
                    $log['custom_sku'] = $v['custom_sku'];
                    $log['num'] = $v['num'];
                    $log['location_id'] = $location_id;
                    $log['time'] = $time;
                    $log['type'] = $type;
                    $log['order_no'] = $order_no ?? '';
                    $log['user_id'] = $user_id;
                    $log['platform_id'] = $platform_id;
                    if(isset($locationArr[$v['id']])){
                        if($type==1){
                            $balance = $v['num'] + $locationArr[$v['id']];
                            if(isset($locationAll[$v['id']])){
                                $balanceAll = $v['num'] + $locationAll[$v['id']];
                            }

                        }elseif ($type==2){
                            $balance = $locationArr[$v['id']] - $v['num'];
                            if(isset($locationAll[$v['id']])) {
                                $balanceAll = $locationAll[$v['id']] - $v['num'];
                            }
                            if($balance<0){
                                throw new \Exception('操作失败--'.$v['custom_sku'].'库位库存不足');
                            }
                        }elseif ($type == 3||$type == 5){
                            $balance = $v['num'] + $locationArr[$v['id']]; // 增加对应库位库存
                            if(isset($locationAll[$v['id']])) {
                                $balanceAll = $v['num'] + $locationAll[$v['id']];
                            }
                        }elseif ($type == 6){
                            $balance = $locationArr[$v['id']] - $v['num']; // 减去对应库位库存
                            if(isset($locationAll[$v['id']])) {
                                $balanceAll = $locationAll[$v['id']] - $v['num'];
                            }
                            if($balance<0){
                                throw new \Exception('操作失败--'.$v['custom_sku'].'库位库存不足');
                            }
                        }
                        $update = DB::table('cloudhouse_location_num')->where('location_id',$location_id)->where('platform_id',$platform_id)->where('custom_sku_id',$v['id'])->update(['num'=>$balance,'update_time'=>time()]);
                        if(!$update){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'操作失败--'.$v['custom_sku']];
                        }
                        $log['now_num'] = $balanceAll??0;
                        $log['now_platform_num'] = $balance;
                        $insertlog = DB::table('cloudhouse_location_log')->insert($log);
                        if(!$insertlog){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'新增日志失败--'.$v['custom_sku']];
                        }
                    }else{
                        if($type==2){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'当前库位没有此产品--'.$v['custom_sku']];
                        }
                        $insert['spu'] = $v['spu'];
                        $insert['spu_id'] = $this->GetSpuId($v['spu']);
                        $insert['custom_sku_id'] = $v['id'];
                        $insert['custom_sku'] = $v['custom_sku'];
                        $insert['num'] = $v['num'];
                        $insert['create_time'] = time();
                        $insert['location_id'] = $location_id;
                        $insert['platform_id'] = $platform_id;
                        $insertdata = DB::table('cloudhouse_location_num')->insert($insert);
                        if(!$insertdata){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'操作失败--'.$v['custom_sku']];
                        }

                        $log['now_num'] = $v['num'];
                        $log['now_platform_num'] = $v['num'];
                        $insertlog = DB::table('cloudhouse_location_log')->insert($log);
                        if(!$insertlog){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'新增日志失败--'.$v['custom_sku']];
                        }
                    }
                    if ($type == 3){
                        $box_total += $v['num'];
                        $this_now_num = $v['num'];
                        $i = 0;
                        do {
                            $this_now_num -= $shelf_numArr[$i]['shelf_num'];
                            if ($this_now_num > 0) {
                                db::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id'])
                                    ->where('location_ids', $shelf_numArr[$i]['location_id'])->update(['shelf_num'=>0]);
                            } else {
                                db::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id'])
                                    ->where('location_ids', $shelf_numArr[$i]['location_id'])
                                    ->update(['shelf_num'=>$shelf_numArr[$i]['shelf_num']-($this_now_num+$shelf_numArr[$i]['shelf_num'])]);
                            }
                            $i++;
                        } while ($this_now_num > 0);
                    }elseif($type==1||$type==2){

                        $update_boxDetail = DB::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id']);
                        if($type==2){
                            $update_boxDetail = $update_boxDetail->where('location_ids',$location_id);
                        }

                        $updateArr['shelf_num'] = $v['num']+$shelf_num;
                        $update_boxDetail = $update_boxDetail->update($updateArr);
                        $box_total += $v['num'];
                        if(!$update_boxDetail){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'操作失败--'.$v['custom_sku']];
                        }

                        if($type==1){
                            //普通上架直接入库
                            if($type_detail==2){
                                if(!isset($contractArr[$v['id']])){
                                    $ts = json_encode( $contractArr);
                                    return ['code' => 500, 'msg' => '新增资产记录失败--无此库存sku合同号1-'.$v['id'].'-'.$ts];
                                }
                                $custom_sku_pirce = DB::table('cloudhouse_custom_sku')->where('custom_sku_id',$v['id'])
                                    ->where('contract_no',$contractArr[$v['id']])->select('price')->first();
                                if(empty($custom_sku_pirce)){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '未查询到合同单价--' . $v['custom_sku']];
                                }
                                $query['price'] = $custom_sku_pirce->price;
                            }else{
                                $query['price'] = $this->GetCloudHousePrice($warehouse_id, $v['id']);
                            }

                            $query['warehouse_id'] = $warehouse_id;
                            $query['custom_sku_id'] = $v['id'];

                            $query['num'] = $v['num'];
                            $query['user_id'] = $user_id;
                            $query['type'] = 2; //1为出2为入
                            $res = $this->UpCloudHousePrice($query);
                            if ($res['type'] != 'success') {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                            }

                            $insertRecord['order_no'] = $order_no;
                            $insertRecord['spu'] = $v['spu'];
                            $insertRecord['spu_id'] = $this->GetSpuId($v['spu']);
                            $insertRecord['custom_sku_id'] = $v['id'];
                            $insertRecord['custom_sku'] = $v['custom_sku'];
                            $insertRecord['num'] = $v['num'];
                            $insertRecord['createtime'] = date('Y-m-d H:i:s');
                            $insertRecord['type'] = 2;
                            $insertRecord['user_id'] = $user_id;
                            $insertRecord['type_detail'] = $type_detail;
                            $insertRecord['warehouse_id'] = $warehouse_id;
                            $insertRecord['shop_id'] = $goods_transfers->shop_id;
                            $increase_num = $inventoryArr[$v['id']][self::WAREHOUSE[$warehouse_id]] + $v['num'];
                            $modify2Update[self::WAREHOUSE[$warehouse_id]] = $increase_num;
                            $modify2 = DB::table('self_custom_sku')->where('id', $v['id'])->update($modify2Update);

                            $insertRecord['price'] = $query['price'];
                            $insertRecord['now_inventory'] = $increase_num;
                            $insertRecord['now_total_price'] = $res['total_price'];
                            $insertIn = DB::table('cloudhouse_record')->insert($insertRecord);
                            if (!$insertIn) {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
                            }
                            if(isset($transfersDetail[$v['id']])){
                                $updateDetailNum = $transfersDetail[$v['id']]->receive_num + $v['num'];
                                if($updateDetailNum>$transfersDetail[$v['id']]->transfers_num){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '入库数量超过清单数量--' . $v['custom_sku']];
                                }else{
                                    $goods_transfers_detail_one = DB::table('goods_transfers_detail')->where('id',$transfersDetail[$v['id']]->id)->first();
                                    $receive_num_arr = json_decode($goods_transfers_detail_one->receive_num_arr,true);

                                    $receive_num_arr[$platform_id]=$updateDetailNum;

                                    

                                    $updateThisDetail = DB::table('goods_transfers_detail')->where('id',$transfersDetail[$v['id']]->id)->update(['receive_num'=>$updateDetailNum,'receive_num_arr'=>json_encode($receive_num_arr)]);
                                    if(!$updateThisDetail){
                                        db::rollback();// 回调
                                        return ['code' => 500, 'msg' => '修改实际入库数量失败--' . $v['custom_sku']];
                                    }
                                }

                            }else{
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '入库明细中无此sku数据--' . $v['custom_sku']];
                            }

                        }
                        //入库结束
                    }
                }
            }

            if ($type == 3){
                $onshelf_balance_num = $onshelf_num - $box_total;
                if($onshelf_balance_num==0){
                    DB::table('goods_transfers')->where('order_no',$order_no)->update(['is_push'=>2]);
                }
                DB::table('goods_transfers_box')->where('id',$box_id)->update(['onshelf_num'=>$onshelf_balance_num]);
            }elseif($type==1||$type==2){
                $receive_num = $onshelf_num+$box_total;
                if($receive_num == $boxData->box_num){
                    DB::table('goods_transfers_box')->where('id',$box_id)->update(['onshelf_num'=>$receive_num,'status'=>2]);
                }else{
                    DB::table('goods_transfers_box')->where('id',$box_id)->update(['onshelf_num'=>$receive_num]);
                }

            }
            db::commit();
            if(isset($type_detail)){
                if($type_detail==15){
                    return ['code'=>300,'msg'=>'操作成功','order_no'=>$order_no];
                }else{
                    return ['code'=>200,'msg'=>'操作成功'];
                }
            }else{
                return ['code'=>200,'msg'=>'操作成功'];
            }

        }catch (\Exception $e){
            db::rollback();
            return ['code'=>500,'msg'=>'操作失败--'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }


    //包装-获取产品
    public function V1GetProduct($params){
        $product = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->leftjoin('self_custom_sku as c','a.custom_sku_id','=','c.id')->whereIn('b.is_push',[2,4])->where('type_detail',2)->select('b.order_no','a.custom_sku_id','c.custom_sku','c.old_custom_sku','c.box_num','c.name');
        $product = $product->where('c.old_custom_sku',$params['custom_sku']);
        $product = $product->first();
        $data = [];
        if($product){
            $data['img'] = $this->GetCustomskuImg($product->custom_sku);
            $data['box_num'] = $product->box_num;
            $data['custom_sku'] = $product->old_custom_sku;
            $data['custom_sku_id'] = $product->custom_sku_id;
            $data['order_no'] = $product->order_no;
            $data['name'] = $product->name;
        }

        return ['type'=>'success','data'=>$data,'msg'=>'获取成功'];
    }

    //包装
    public function V1PackIn($params){
        $data = $params['data'];
        $user_id = $params['user_id'];
        $is_commit = $params['is_commit']??0;
        foreach ($data as $v) {
            db::table('goods_transfers')->where('order_no',$v['order_no'])->update(['is_push'=>4]); 
            $gtd = db::table('goods_transfers_detail')->where('order_no',$v['order_no'])->where('custom_sku_id',$v['custom_sku_id'])->first();
            $pack_num = $gtd->pack_num +$v['num'];

    

            if($is_commit==0){
                if($gtd->transfers_num<$pack_num){
                    return ['type'=>'fail','msg'=>'检测到当前sku数量超出入库单推送数量，请确认是否贴错条码'.$v['custom_sku']];
                }
            }
 
            # code...
            $log['order_no'] = $v['order_no'];
            $log['custom_sku_id'] = $v['custom_sku_id'];
            $log['custom_sku'] = $v['custom_sku'];
            $log['num'] = $v['num'];
            $log['user_id'] =  $user_id;
            $log['create_time'] =  date('Y-m-d  H:i:s',time());
            db::table('goods_transfers_detail')->where('id',$gtd->id)->update(['pack_num'=>$pack_num]);
            // $log_is = db::table('goods_transfers_pack_log')->where('user_id',$user_id)->where('status',0)->where('order_no',$v['order_no'])->where('custom_sku_id',$v['custom_sku_id'])->first();


            // if($log_is){
            //     $new_num = $log_is->num = $v['num'];
            //     db::table('goods_transfers_pack_log')->where('id',$log_is->id)->update(['num'=>$new_num]);
            // }else{
                // db::table('goods_transfers_pack_log')->insert($log);
            // }

            db::table('goods_transfers_pack_log')->insert($log);


        }

        return ['type'=>'success','msg'=>'操作成功'];

    }


    public function V1PackLog($params){
        $list = db::table('goods_transfers_pack_log');
        if(isset($params['order_no'])){
            $list = $list->where('order_no',$params['order_no']);
        }
        if(isset($params['user_id'])){
            $list = $list->where('user_id',$params['user_id']);
        }
        if(isset($params['user_id'])){
            $list = $list->where('user_id',$params['user_id']);
        }

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $list = $list->whereBetween('create_time', [$params['start_time'], $params['end_time']]);
        }


        $list = $list->get();
        foreach ($list as $v) {
            # code...
            $v->user = $this->GetUsers($v->user_id)['account'];
        }

        return ['type'=>'success','msg'=>'获取成功','data'=>$list];
    }


    public function V1SaveLog($params){
        $list = db::table('goods_transfers_save_log');
        if(isset($params['order_no'])){
            $list = $list->where('order_no',$params['order_no']);
        }
        if(isset($params['user_id'])){
            $list = $list->where('user_id',$params['user_id']);
        }

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $list = $list->whereBetween('create_time', [$params['start_time'], $params['end_time']]);
        }
        $list = $list->get();
        foreach ($list as $v) {
            # code...
            $v->user = $this->GetUsers($v->user_id)['account'];
            $v->ys_user = $this->GetUsers($v->ys_user_id)['account'];
        }

        return ['type'=>'success','msg'=>'获取成功','data'=>$list];
    }



    //收货-获取产品
    public function V1SaveProduct($params){


        $product = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->leftjoin('self_custom_sku as c','a.custom_sku_id','=','c.id')->where('b.is_push',4)->where('type_detail',2)->select('b.order_no','a.custom_sku_id','c.custom_sku','c.old_custom_sku','c.box_num','c.name');
        $product = $product->where('c.old_custom_sku',$params['custom_sku']);
        $product = $product->first();
        $data = [];
        if($product){
            $data['img'] = $this->GetCustomskuImg($product->custom_sku);
            $data['box_num'] = $product->box_num;
            $data['custom_sku'] = $product->old_custom_sku;
            $data['custom_sku_id'] = $product->custom_sku_id;
            $data['order_no'] = $product->order_no;
            $data['name'] = $product->name;
        }else{
            return ['type'=>'fail','msg'=>'无此产品或没有正在进行的单'];
        }


        $is_commit = $params['is_commit']??0;

        if($is_commit==0){
            $ReceiveProduct = db::table('goods_transfers_pack_log')->where('order_no',$product->order_no)->where('user_id',$params['user_id'])->where('custom_sku',$params['custom_sku'])->first();
            if(!$ReceiveProduct){
                return ['type'=>'fail','msg'=>'无此包装工数据'];
            }
        }

        // $cus = db::table('self_custom_sku')->where('custom_sku',$params['custom_sku'])->orwhere('old_custom_sku',$params['custom_sku'])->first();

        // $data = [];
        // if($cus){
        //     $data['img'] = $this->GetCustomskuImg($cus->custom_sku);
        //     $data['box_num'] = $cus->box_num;
        //     $data['custom_sku'] =$params['custom_sku'];
        //     $data['custom_sku_id'] = $cus->id;
        //     $data['order_no'] = $ReceiveProduct->order_no;
        //     $data['name'] = $cus->name;
        //     $data['log_id'] = $ReceiveProduct->id;
        // }else{
        //     return ['type'=>'fail','msg'=>'无此产品数据'];
        // }

        return ['type'=>'success','data'=>$data,'msg'=>'获取成功'];
    }

    //收货
    public function V1SaveIn($params){
        $data = $params['data'];
        $user_id = $params['user_id'];
        $is_commit = $params['is_commit']??0;
        foreach ($data as $v) {

            
            $gtd = db::table('goods_transfers_detail')->where('order_no',$v['order_no'])->where('custom_sku_id',$v['custom_sku_id'])->first();
            $save_num = $gtd->save_num +$v['num'];

    

           
            if($is_commit!=1){
                if($gtd->pack_num<$save_num){
                    return ['type'=>'fail','msg'=>'检测到当前sku数量超出包装数量，请确认是否贴错条码'.$v['custom_sku']];
                }
            }

            
  
            # code...
            $log['order_no'] = $v['order_no'];
            $log['custom_sku_id'] = $v['custom_sku_id'];
            $log['custom_sku'] = $v['custom_sku'];
            $log['num'] = $v['num'];
            $log['user_id'] =  $user_id;
            $log['create_time'] =  date('Y-m-d H:i:s',time());

            db::table('goods_transfers_save_log')->insert($log);

            // db::table('goods_transfers_pack_log')->where('id',$v['log_id'])->update(['status'=>1]);

            db::table('goods_transfers_detail')->where('id',$gtd->id)->update(['save_num'=>$save_num]);

            // $log_is = db::table('goods_transfers_save_log')->where('user_id',$user_id)->where('status',0)->where('order_no',$v['order_no'])->where('custom_sku_id',$v['custom_sku_id'])->first();

            // db::table('goods_transfers_detail')->where('id',$gtd->id)->update(['save_num'=>$save_num]);
            // if($log_is){
            //     $new_num = $log_is->num = $v['num'];
            //     db::table('goods_transfers_pack_log')->where('id',$log_is->id)->update(['num'=>$new_num]);
            // }else{
            //     db::table('goods_transfers_pack_log')->insert($log);
            // }


        }

        return ['type'=>'success','msg'=>'操作成功'];

    }


     //入库-获取产品
     public function V1Confim($params){
        db::table('goods_transfers')->where('order_no',$params['order_no'])->update(['is_push'=>3]);
        return ['type'=>'success','data'=>$data,'msg'=>'获取成功'];
    }


    //入库-获取产品
    public function V1ReceiveProductOld($params){


        $product = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->leftjoin('self_custom_sku as c','a.custom_sku_id','=','c.id')->where('b.is_push',4)->where('type_detail',2)->select('b.order_no','a.custom_sku_id','c.custom_sku','c.old_custom_sku','c.box_num','c.name');
        $product = $product->where('c.old_custom_sku',$params['custom_sku']);
        $product = $product->first();
        $data = [];
        if($product){
            $data['img'] = $this->GetCustomskuImg($product->custom_sku);
            $data['box_num'] = $product->box_num;
            $data['custom_sku'] = $product->old_custom_sku;
            $data['custom_sku_id'] = $product->custom_sku_id;
            $data['order_no'] = $product->order_no;
            $data['name'] = $product->name;
        }else{
            return ['type'=>'fail','msg'=>'无此产品或没有正在进行的单'];
        }


        $is_commit = $params['is_commit']??0;

        if($is_commit==0){
            $ReceiveProduct = db::table('goods_transfers_save_log')->where('order_no',$product->order_no)->where('custom_sku',$params['custom_sku'])->first();
            if(!$ReceiveProduct){
                return ['type'=>'fail','msg'=>'无此收货数据'];
            }
        }
        // $ReceiveProduct = db::table('goods_transfers_save_log')->where('status',0)->where('custom_sku',$params['custom_sku'])->first();

        // $data = [];
        // if($ReceiveProduct){
        //     $cus = db::table('self_custom_sku')->where('id',$ReceiveProduct->custom_sku_id)->first();
        //     $data['img'] = $this->GetCustomskuImg($ReceiveProduct->custom_sku);
        //     $data['box_num'] = $cus->box_num;
        //     $data['custom_sku'] = $ReceiveProduct->custom_sku;
        //     $data['custom_sku_id'] = $ReceiveProduct->custom_sku_id;
        //     $data['order_no'] = $ReceiveProduct->order_no;
        //     $data['name'] = $cus->name;
        //     $data['log_id'] = $ReceiveProduct->id;
        // }

        return ['type'=>'success','data'=>$data,'msg'=>'获取成功'];
    }

    
    //包装-获取产品
    public function V1ReceiveProduct($params){
        $product = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->leftjoin('self_custom_sku as c','a.custom_sku_id','=','c.id')->whereIn('b.is_push',[2,4])->where('type_detail',2)->select('b.order_no','a.custom_sku_id','c.custom_sku','c.old_custom_sku','c.box_num','c.name');
        $product = $product->where('c.old_custom_sku',$params['custom_sku'])->orwhere('c.custom_sku',$params['custom_sku']);
        $product = $product->first();
        $data = [];
        if($product){
            $data['img'] = $this->GetCustomskuImg($product->custom_sku);
            $data['box_num'] = $product->box_num;
            $data['custom_sku'] = $product->old_custom_sku;
            $data['custom_sku_id'] = $product->custom_sku_id;
            $data['order_no'] = $product->order_no;
            $data['name'] = $product->name;
        }

        return ['type'=>'success','data'=>$data,'msg'=>'获取成功'];
    }
    //入库
    public function V1ReceiveIn($params){
        $data = $params['data'];
        $user_id = $params['user_id'];
        $location_id = 8;
        $ys_user_id = $params['ys_user_id']??0;

        $platform_id = $params['platform_id']??1;
        $warehouse_id = 1;

        $is_commit = $params['is_commit']??0;
        db::beginTransaction();    //开启事务
        //校验数据
        foreach ($data as $v) {
            $cus = db::table('self_custom_sku')->where('id',$v['custom_sku_id'])->first();

            $gtd = db::table('goods_transfers_detail')->where('order_no',$v['order_no'])->where('custom_sku_id',$v['custom_sku_id'])->first();

            $gt = db::table('goods_transfers')->where('order_no',$v['order_no'])->first();
            $receive_num = $gtd->receive_num +$v['num'];

            

            $gtreceive_num =$gt->receive_total_num +$v['num'];

            if($is_commit!=1){
                if($gtd->transfers_num<$receive_num){
                    return ['type'=>'fail','msg'=>'检测到当前入库sku数量超出调拨数量，请确认是否贴错条码'.$v['custom_sku']];
                }
            }

            // db::table('goods_transfers_save_log')->where('id',$v['log_id'])->update(['status'=>1]);
            db::table('goods_transfers')->where('id',$gt->id)->update(['receive_total_num'=>$gtreceive_num]);

            // db::table('goods_transfers_detail')->where('id',$gtd->id)->update(['save_num'=>$save_num]);
            // $ReceiveProduct = db::table('goods_transfers_pack_log')->where('status',0)->where('custom_sku_id',$v['custom_sku_id'])->first();
            // $receive_num = $ReceiveProduct->receive_num+$v['num'];
            // if($receive_num >$ReceiveProduct->num){
            //     return ['type'=>'fail','msg'=>'检测到当前sku数量超出包装数量，请确认是否贴错条码'.$v['custom_sku']];
            // }
            // if($receive_num==$ReceiveProduct->num){
            //     db::table('goods_transfers_pack_log')->where('id',$ReceiveProduct->id)->update(['receive_num'=>$receive_num,'status'=>1]);
            // }

            // if($receive_num < $ReceiveProduct->num){
            //     db::table('goods_transfers_pack_log')->where('id',$ReceiveProduct->id)->update(['receive_num'=>$receive_num]);
            // }

                   
             db::table('goods_transfers_detail')->where('order_no',$v['order_no'])->where('custom_sku_id',$v['custom_sku_id'])->update(['receive_num'=>$receive_num]);

        


            //查询

            $location_num = DB::table('cloudhouse_location_num')->where('location_id',$location_id)->where('platform_id',$platform_id)->where('custom_sku_id',$v['custom_sku_id'])->first();
            if($location_num){
                $now_num = $location_num->num + $v['num'];
  
                DB::table('cloudhouse_location_num')->where('id',$location_num->id)->update(['num'=>$now_num]);
            }else{
                $cln['custom_sku'] = $v['custom_sku'];
                $cln['spu'] = $cus->spu;
                $cln['custom_sku_id'] = $v['custom_sku_id'];
                $cln['spu_id'] = $cus->spu_id;
                $cln['num'] = $v['num'];
                $cln['location_id'] = $location_id;
                $cln['platform_id'] = $platform_id;
                $cln['create_time'] = date('Y-m-d H:i:s',time());
                $cln['update_time'] =  date('Y-m-d H:i:s',time());
                DB::table('cloudhouse_location_num')->insert($cln);
                $now_num =  $v['num'];
            }



            // $log['now_num'] = $v['num'];
            // $log['now_platform_num'] = $v['num'];
            // $insertlog = DB::table('cloudhouse_location_log')->insert($log);
            // if(!$insertlog){
            //     db::rollback();// 回调
            //     return ['code'=>500,'msg'=>'新增日志失败--'.$v['custom_sku']];
            // }
            $tongan_inventory = $cus->tongan_inventory + $v['num'];
            db::table('self_custom_sku')->where('id',$v['custom_sku_id'])->update(['tongan_inventory'=>$tongan_inventory]);
            
            // $query['price'] = $this->GetCloudHousePrice($warehouse_id, $v['custom_sku_id']);

            // $query['warehouse_id'] = $warehouse_id;
            // $query['custom_sku_id'] = $v['custom_sku_id'];
            // $query['num'] = $v['num'];
            // $query['user_id'] = $user_id;
            // $query['type'] = 1; //1为出2为入
            // $res = $this->UpCloudHousePrice($query);
            // if ($res['type'] != 'success') {
            //     db::rollback();// 回调
            //     return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
            // }

            $insertRecord['order_no'] = $v['order_no'];
            $insertRecord['spu'] =$cus->spu;
            $insertRecord['spu_id'] = $cus->spu_id;
            $insertRecord['custom_sku_id'] = $v['custom_sku_id'];
            $insertRecord['custom_sku'] = $v['custom_sku'];
            $insertRecord['num'] = $v['num'];
            $insertRecord['createtime'] = date('Y-m-d H:i:s');
            $insertRecord['type'] = 2;
            $insertRecord['user_id'] = $user_id;
            $insertRecord['ys_user_id'] = $ys_user_id;
            $insertRecord['type_detail'] = 25;
            $insertRecord['warehouse_id'] = $warehouse_id;
            $insertRecord['shop_id'] = 0;
            $insertRecord['price'] = 0;
            $insertRecord['now_inventory'] = $now_num;
            $insertRecord['now_total_price'] = 0;
            $insertIn = DB::table('cloudhouse_record')->insert($insertRecord);
            if (!$insertIn) {
                db::rollback();// 回调
                return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
            }

            # code...
            $log['order_no'] = $v['order_no'];
            $log['custom_sku_id'] = $v['custom_sku_id'];
            $log['custom_sku'] = $v['custom_sku'];
            $log['num'] = $v['num'];
            $log['user_id'] =  $user_id;
            $log['create_time'] =  date('Y-m-d H:i:s',time());
            $log['platform_id'] = $platform_id;
            $log['ys_user_id'] = $ys_user_id;


            db::table('goods_transfers_save_log')->insert($log);

            // $plat_log['platform_id'] = $platform_id;
            // $plat_log['order_no'] = $v['order_no'];
            // $plat_log['custom_sku_id'] = $v['custom_sku_id'];
            // $plat_log['custom_sku'] = $v['custom_sku'];
            // $plat_log['num'] = $v['num'];
            // $plat_log['user_id'] =  $user_id;
            // $plat_log['create_time'] =  date('Y-m-d',time());
            // db::table('goods_transfers_platform_log')->insert($plat_log);

        }

        db::commit();
        return ['code'=>200,'msg'=>'收货成功'];
    }

    
       //创建压缩出库
       public function ContractOutYsbak($params){

        // Redis::Set('ContractOut',json_encode($params));
        // return ['type'=>'success','msg'=>json_encode($params)];
        
        $detail = array();

        $day = date('Y-m-d',time());
        $order_nums = db::table('goods_transfers')->where('ds',$day)->orderby('ds_num','desc')->first();

        if($order_nums){
            $order_num = $order_nums->order_num+1;
        }else{
            $order_num = 1;
        }
        $out_no = date('Ymd').str_pad($order_num, 3, 0, STR_PAD_LEFT);

        $box_num = 1;//箱数

        $skunum = 0;
        $goodsnum = 0;
        $time = date('Y-m-d H:i:s',time());
        db::beginTransaction();    //开启事务
        $sku_idArr = array();

        $platform_id = $params['platform_id'];
        $warehouse_id = $params['warehouse_id'];
        $location_id = 8;


        $attr['m_title'] = $params['m_title']??'';//唛头
        $attr['long'] = $params['long']??'';//长
        $attr['width']= $params['width']??'';//宽
        $attr['height'] = $params['height']??'';//高
        $attr['photo'] = json_encode($params['photo'])??'';//图片

        $new_data = [];
        foreach ($params['data'] as $v) {
            $is_repaet =  Db::table('goods_transfers_detail')->where('box_code','like','%'.$v['box_code'].'%')->first();
            if($is_repaet){
                db::rollback();// 回调
                return ['code'=>500,'msg'=>'该包装袋已出库，无法出库'];
            }
            $new_data[$v['id']]['id'] = $v['id'];
            $new_data[$v['id']]['custom_sku'] = $v['custom_sku'];
            if(isset($new_data[$v['id']]['num'])){
                $new_data[$v['id']]['num'] += $v['num'];
            }else{
                $new_data[$v['id']]['num']  = $v['num'];
            }
            $new_data[$v['id']]['box_code'][] = $v['box_code'];
        }

        $user_id = $params['user_id']??1;

        // $change = $params['change'];
        foreach ($new_data as $v) {

                $num = $v['num'];
                $box_code = array_unique($v['box_code']);
                $box_code = implode(',',$box_code);
                if($num>0){
              

                    $sku_idArr[] = $v['id'];
                    //sku个数
                    $skunum++;
                    // $detail[]= ['custom_sku'=> $customsku->custom_sku,'num'=>$num];
                    //商品总数
                    $goodsnum += $num;
                    $custom_sku = db::table('self_custom_sku')->where('id',$v['id'])->first();

          
                    $detailinsert['custom_sku'] = $v['custom_sku'];
                    

                    $detailinsert['custom_sku_id'] = $v['id'];
                    $detailinsert['spu_id'] = $custom_sku->spu_id;
                    //调拨数量
                    $detailinsert['transfers_num'] = $num;


                    $detailinsert['receive_num'] = $num;
                    $detailinsert['receive_time'] = $time;

                    
                    //spu
                    $detailinsert['spu'] = $custom_sku->spu;
                    //合同号
                    $detailinsert['contract_no'] = '';
                    //批号
                    $detailinsert['order_no'] = $out_no;
                    //创建时间
                    $detailinsert['createtime'] =  $time;
                    $detailinsert['box_code'] =  $box_code;

                    
                    //插入详情
                    Db::table('goods_transfers_detail')->insert($detailinsert);


                    //查询

                    $location_num = DB::table('cloudhouse_location_num')->where('location_id',$location_id)->where('platform_id',$platform_id)->where('custom_sku_id',$v['id'])->first();
                    if($location_num){
                        $now_num = $location_num->num - $num;
                        if($now_num<0){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'此库位库存不足，无法出库'.$v['custom_sku'].'cus_id:'.$v['id'].'-库位id'.$location_id];
                        }
                        DB::table('cloudhouse_location_num')->where('id',$location_num->id)->update(['num'=>$now_num]);
                    }else{
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'此库位库存不足，无法出库'.$v['custom_sku'].'cus_id:'.$v['id'].'-库位id'.$location_id];
                    }


              

                    $log['now_num'] = $v['num'];
                    $log['now_platform_num'] = $v['num'];
                    $insertlog = DB::table('cloudhouse_location_log')->insert($log);
                    if(!$insertlog){
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'新增日志失败--'.$v['custom_sku']];
                    }
                    $custom_sku->tongan_inventory -= $v['num'];
                    db::table('self_custom_sku')->where('id',$v['id'])->update(['tongan_inventory'=>$custom_sku->tongan_inventory]);
                    
                    $query['price'] = $this->GetCloudHousePrice($warehouse_id, $v['id']);

                    $query['warehouse_id'] = $warehouse_id;
                    $query['custom_sku_id'] = $v['id'];
                    $query['num'] = $v['num'];
                    $query['user_id'] = $user_id;
                    $query['type'] = 1; //1为出2为入
                    $res = $this->UpCloudHousePrice($query);
                    if ($res['type'] != 'success') {
                        db::rollback();// 回调
                        return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                    }

                    $insertRecord['order_no'] = $out_no;
                    $insertRecord['spu'] =$custom_sku->spu;
                    $insertRecord['spu_id'] = $custom_sku->spu_id;
                    $insertRecord['custom_sku_id'] = $v['id'];
                    $insertRecord['custom_sku'] = $v['custom_sku'];
                    $insertRecord['num'] = $v['num'];
                    $insertRecord['createtime'] = date('Y-m-d H:i:s');
                    $insertRecord['type'] = 1;
                    $insertRecord['user_id'] = $user_id;
                    $insertRecord['type_detail'] = 25;
                    $insertRecord['warehouse_id'] = $warehouse_id;
                    $insertRecord['shop_id'] = 0;
                    $insertRecord['price'] = $query['price'];
                    $insertRecord['now_inventory'] = $now_num;
                    $insertRecord['now_total_price'] = $res['total_price'];
                    $insertIn = DB::table('cloudhouse_record')->insert($insertRecord);
                    if (!$insertIn) {
                        db::rollback();// 回调
                        return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
                    }
                }
                

            
            }




        //批号
        $transfersinsert['order_no'] = $out_no;
        //合同号
        $transfersinsert['contract_no'] = json_encode(array_keys($detail));

        // $transfersinsert['img_url'] = isset($params['img_url'])?json_encode($params['img_url']):'';//图片
        // $transfersinsert['file_url'] = isset($params['file_url'])?json_encode($params['file_url']):''??'';//附件

        $transfersinsert['createtime'] =  $time;
        //出库sku数量
        $transfersinsert['sku_count'] = $skunum;
        //出库数量
        $transfersinsert['total_num'] = $goodsnum;
        //实际数量
        $transfersinsert['receive_total_num'] = $goodsnum;
        //箱数
        $transfersinsert['box_num'] = $box_num;
        //平台
        $transfersinsert['platform_id'] = $platform_id;
        //入库仓库
        $transfersinsert['in_house'] = 1;
        //出仓仓库
        $transfersinsert['out_house'] = 1;
        //出库用户
        $transfersinsert['user_id'] = $params['user_id'];

        $transfersinsert['anomaly_order'] =  $params['anomaly_order']??'';
        $transfersinsert['text'] =  $params['text']??'';
        $transfersinsert['type'] = 25;

        $transfersinsert['is_qc'] = $params['is_qc'] ?? 0;

        $transfersinsert['is_push'] = 3;
        $transfersinsert['status'] = 4;
        $transfersinsert['type_detail'] = 25;
        $transfersinsert['attr'] = json_encode($attr);
    
        Db::table('goods_transfers')->insert($transfersinsert);

        db::commit();

        return ['type'=>'success','code'=>200,'msg'=>'出货成功','data'=> [$out_no]];
    }


        //创建压缩出库
        public function ContractOutYsNew($params){

            $step = $params['step']??1;

            $ys_user_id = $params['ys_user_id']??1;
            $order_no = $params['order_no'];

            $goods_transfers =  db::table('goods_transfers')->where('order_no',$order_no)->first();

            if($step==2){
                $attr['m_title'] = $params['m_title']??'';//唛头
                $attr['long'] = $params['long']??'';//长
                $attr['width']= $params['width']??'';//宽
                $attr['height'] = $params['height']??'';//高
                $attr['weight'] = $params['weight']??'';//重量
                $attr['desc'] = $params['desc']??'';//备注
                $photo = $params['photo']??[];
                $attr['photo'] = json_encode($photo);//图片
                db::table('goods_transfers')->where('id',$goods_transfers->id)->update(['attr'=>json_encode($attr),'is_push'=>3]);
                return ['type'=>'success','code'=>200,'msg'=>'回填成功','data'=> [$order_no]];
            }

   
    
            $platform_id = $goods_transfers->platform_id;
            $warehouse_id = $params['warehouse_id']??1;
            $user_id = $params['user_id']??1;

     


            db::beginTransaction();    //开启事务
            if(!$goods_transfers){
                return ['code'=>500,'msg'=>'无此压缩包，请先创建'];
            }

            $new_data =$params['data'] ;

            $total_num = 0;
            foreach ($new_data as $v) {
                # code...
                $num = $v['num'];
                // $box_code = array_unique($v['box_code']);
                // $box_code = implode(',',$box_code);
                if($num>0){
                    $total_num+=$num;
                   $custom_sku_id = $v['id'];

                   $detail = db::table('goods_transfers_detail')->where('custom_sku_id', $custom_sku_id)->where('order_no',$order_no)->first();

                   if(!$detail){
                    db::rollback();// 回调
                    return ['code'=>500,'msg'=>'无此出库计划，请确认国家或sku是否正确'];
                   }
                   $d_receive_num = $detail->receive_num+$num;
                   if($d_receive_num>$detail->transfers_num){
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'出库数量大于计划数量'];
                   }

                   db::table('goods_transfers_detail')->where('id', $detail->id)->update(['receive_num'=>$d_receive_num]);

                   $custom_sku = db::table('self_custom_sku')->where('id',$v['id'])->first();
                   $tongan_inventory = $custom_sku->tongan_inventory - $v['num'];
                    if($tongan_inventory<0){
                        db::rollback();// 回调
                        return ['code'=>500,'msg'=>'总库存不足 无法出库'];
                    }
                   db::table('self_custom_sku')->where('id',$v['id'])->update(['tongan_inventory'=>$tongan_inventory]);

                   $insertRecord['order_no'] = $order_no;
                   $insertRecord['spu'] =$custom_sku->spu;
                   $insertRecord['spu_id'] = $custom_sku->spu_id;
                   $insertRecord['custom_sku_id'] = $v['id'];
                   $insertRecord['custom_sku'] = $custom_sku->old_custom_sku;
                   $insertRecord['num'] = $v['num'];
                   $insertRecord['createtime'] = date('Y-m-d H:i:s');
                   $insertRecord['type'] = 1;
                   $insertRecord['user_id'] = $user_id;
                   $insertRecord['type_detail'] = 25;
                   $insertRecord['warehouse_id'] = $warehouse_id;
                   $insertRecord['shop_id'] = 0;
                   $insertRecord['price'] = 0;
                   $insertRecord['now_inventory'] = $tongan_inventory;
                   $insertRecord['now_total_price'] = 0;
                   $insertRecord['ys_user_id'] =$ys_user_id;
                   $insertIn = DB::table('cloudhouse_record')->insert($insertRecord);
                   if (!$insertIn) {
                       db::rollback();// 回调
                       return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
                   }


                   $is_p_log = db::table('goods_transfers_platform_log')->where('order_no',$order_no)->where('platform_id',$platform_id)->where('custom_sku_id',$v['id'])->first();

                   $p_log_i['order_no'] = $order_no;
                   $p_log_i['custom_sku_id'] =  $v['id'];
                   $p_log_i['custom_sku'] =  $insertRecord['custom_sku'];
  
                   $p_log_i['user_id'] = $user_id;
                   $p_log_i['ys_user_id'] = $ys_user_id;
                   $p_log_i['create_time'] =date('Y-m-d H:i:s');
                   $p_log_i['platform_id'] = $platform_id;
                   if($is_p_log){
                       $p_log_i['receive_num'] = $is_p_log->receive_num+$num;
                       db::table('goods_transfers_platform_log')->where('id',$is_p_log->id)->update(['receive_num'=>$p_log_i['receive_num']]);
                   }else{
                       $p_log_i['receive_num'] = $num;
                       db::table('goods_transfers_platform_log')->insert($p_log_i);
                   }
                   
                }
            }


            $receive_total_num = $goods_transfers->receive_total_num + $total_num;
            
            // if($receive_total_num== $goods_transfers->total_num){
            //     $is_push=3;
            // }else{
            //     $is_push=4;
            // }
            db::table('goods_transfers')->where('id',$goods_transfers->id)->update(['receive_total_num'=>$receive_total_num,'is_push'=>4]);

            db::commit();
            return ['type'=>'success','code'=>200,'msg'=>'出货成功','data'=> [$order_no]];
        }


        
    public function httpcopys($url,$order_no){
        $remote_pdf_url = $url;
        $remote_pdf_url = urldecode($remote_pdf_url);
        $file_name = basename($remote_pdf_url);
    
        $local_path = '/var/www/test/xin/public/qrcode/'.$order_no.'.png';
        if (file_exists($local_path)) {
            return $local_path;
        } 
    
        // 下载远程 PDF 文件并保存到本地服务器
        $file_content = file_get_contents($remote_pdf_url);
        if ($file_content !== false) {
            file_put_contents($local_path, $file_content);
            return $local_path;
        } else {
            return false;
        }
    }


       //创建压缩出库
       public function ContractOutYs($params){

        // Redis::Set('ContractOut',json_encode($params));
        // return ['type'=>'success','msg'=>json_encode($params)];
        
        $detail = array();

        $day = date('Y-m-d',time());
        $order_nums = db::table('goods_transfers')->where('ds',$day)->orderby('ds_num','desc')->first();

        if($order_nums){
            $order_num = $order_nums->ds_num+1;
        }else{
            $order_num = 1;
        }
        $out_no = date('Ymd').str_pad($order_num, 3, 0, STR_PAD_LEFT);

        $table = db::table('sys')->first()->table;
        try {
            //code...
            if($table=='online'){
                $this->httpcopys('https://api.nbhao.org/v1/qrcode/make?text=http://116.62.169.253:9090/ys_detail.php?order_no='.$out_no,$out_no);
            }else{
                $this->httpcopys('https://api.nbhao.org/v1/qrcode/make?text=http://116.62.169.253:9080/ys_detail.php?order_no='.$out_no,$out_no);
            }
     
        } catch (\Throwable $th) {
            //throw $th;
            return ['type'=>'fail','code'=>500,'msg'=>'预生成二维码失败'];
        }

 
        $box_num = 1;//箱数

        $skunum = 0;
        $goodsnum = 0;
        $time = date('Y-m-d H:i:s',time());
        db::beginTransaction();    //开启事务
        $sku_idArr = array();

        $platform_id = $params['platform_id'];
        $warehouse_id = $params['warehouse_id']??1;
        $location_id = 8;


        // $order_no = $params['order_no'];
        $attr['m_title'] = $params['m_title']??'';//唛头
        $attr['long'] = $params['long']??'';//长
        $attr['width']= $params['width']??'';//宽
        $attr['height'] = $params['height']??'';//高
        $attr['weight'] = $params['weight']??'';//重量
        $photo = $params['photo']??[];

        $attr['photo'] = json_encode($photo);//图片

        $new_data =$params['data'] ;
        // foreach ($params['data'] as $v) {
        //     $is_repaet =  Db::table('goods_transfers_detail')->where('box_code','like','%'.$v['box_code'].'%')->first();
        //     if($is_repaet){
        //         db::rollback();// 回调
        //         return ['code'=>500,'msg'=>'该包装袋已出库，无法出库'];
        //     }
        //     $new_data[$v['id']]['id'] = $v['id'];
        //     $new_data[$v['id']]['custom_sku'] = $v['custom_sku'];
        //     if(isset($new_data[$v['id']]['num'])){
        //         $new_data[$v['id']]['num'] += $v['num'];
        //     }else{
        //         $new_data[$v['id']]['num']  = $v['num'];
        //     }
        //     $new_data[$v['id']]['box_code'][] = $v['box_code'];
        // }

        $user_id = $params['user_id']??1;

        // $change = $params['change'];
        foreach ($new_data as $v) {

                $num = $v['request_num'];
                // $box_code = array_unique($v['box_code']);
                // $box_code = implode(',',$box_code);
                if($num>0){
              

                    
                    $sku_idArr[] = $v['custom_sku_id'];
                    //sku个数
                    $skunum++;
                    // $detail[]= ['custom_sku'=> $customsku->custom_sku,'num'=>$num];
                    //商品总数
                    $goodsnum += $num;
                    $custom_sku = db::table('self_custom_sku')->where('id',$v['custom_sku_id'])->first();

                    if($custom_sku->old_custom_sku){
                        $detailinsert['custom_sku'] = $custom_sku->old_custom_sku;
                    }else{
                        $detailinsert['custom_sku'] = $custom_sku->custom_sku;
                    }
          
                   
                    

                    $detailinsert['custom_sku_id'] = $v['custom_sku_id'];
                    $detailinsert['spu_id'] = $custom_sku->spu_id;
                    //调拨数量
                    $detailinsert['transfers_num'] = $num;


                    $detailinsert['receive_num'] = 0;
                    $detailinsert['receive_time'] = $time;

                    
                    //spu
                    $detailinsert['spu'] = $custom_sku->spu;
      
                    //批号
                    $detailinsert['order_no'] = $out_no;
                    //创建时间
                    $detailinsert['createtime'] =  $time;
                    $detailinsert['platform_id'] =  $platform_id;
                    // $detailinsert['box_code'] =  $box_code;

                    if(isset($v['order_no'])){
                        $order_no = $v['order_no']; 
                    }else{
                        return ['type'=>'fail','code'=>500,'msg'=>'子数据请传输单号order_no'];
                    }
                    
         
                    $is_out_g = db::table('goods_transfers_detail')->where('order_no',$order_no)->where('custom_sku_id',$v['custom_sku_id'])->first();
                    //合同号
                    $detailinsert['contract_no'] = $is_out_g->contract_no;
                    // if($is_out_g->is_push!=3){
                    //     return ['type'=>'fail','code'=>500,'msg'=>'该订单尚未完成，无法出库'.$order_no];
                    // }
                    

                    $inventory = db::table('self_custom_sku')->where('id',$v['custom_sku_id'])->first();
 
                    if($inventory->tongan_inventory<$num){
                        return ['type'=>'fail','code'=>500,'msg'=>$v['custom_sku_id'].'库存不足，无法出库'.$order_no];
                    }
                    //插入详情
                    Db::table('goods_transfers_detail')->insert($detailinsert);

                    

                    $is_p_log = db::table('goods_transfers_platform_log')->where('order_no',$out_no)->where('platform_id',$platform_id)->where('custom_sku_id',$v['custom_sku_id'])->first();

                    $p_log_i['order_no'] = $out_no;
                    $p_log_i['custom_sku_id'] = $v['custom_sku_id'];
                    $p_log_i['custom_sku'] = $detailinsert['custom_sku'];
   
                    $p_log_i['user_id'] = $user_id;
                    $p_log_i['create_time'] = $time;
                    $p_log_i['platform_id'] = $platform_id;
                    $p_log_i['out_no'] =  $order_no;
                    if($is_p_log){
                        $p_log_i['transfers_num'] = $is_p_log->transfers_num+$num;
                        db::table('goods_transfers_platform_log')->where('id',$is_p_log->id)->update(['transfers_num'=>$p_log_i['transfers_num']]);
                    }else{
                        $p_log_i['transfers_num'] = $num;
                        db::table('goods_transfers_platform_log')->insert($p_log_i);
                    }

                }
                

            
            }



        $transfersinsert['out_no'] =  '';
        //批号
        $transfersinsert['order_no'] = $out_no;
        //合同号
        $transfersinsert['contract_no'] = json_encode(array_keys($detail));

        // $transfersinsert['img_url'] = isset($params['img_url'])?json_encode($params['img_url']):'';//图片
        // $transfersinsert['file_url'] = isset($params['file_url'])?json_encode($params['file_url']):''??'';//附件

        $transfersinsert['createtime'] =  $time;
        //出库sku数量
        $transfersinsert['sku_count'] = $skunum;
        //出库数量
        $transfersinsert['total_num'] = $goodsnum;
        //实际数量
        $transfersinsert['receive_total_num'] = 0;
        //箱数
        $transfersinsert['box_num'] = $box_num;
        //平台
        $transfersinsert['platform_id'] = $platform_id;
        //入库仓库
        $transfersinsert['in_house'] = 1;
        //出仓仓库
        $transfersinsert['out_house'] = 1;
        //出库用户
        $transfersinsert['user_id'] = $params['user_id'];

        $transfersinsert['anomaly_order'] =  $params['anomaly_order']??'';
        $transfersinsert['text'] =  $params['text']??'';
        $transfersinsert['type'] = 25;

        $transfersinsert['is_qc'] = $params['is_qc'] ?? 0;

        $transfersinsert['is_push'] = 2;
        $transfersinsert['status'] = 4;
        $transfersinsert['type_detail'] = 25;
        $transfersinsert['attr'] = json_encode($attr);

        $transfersinsert['ds'] = $day; 
        $transfersinsert['ds_num'] =  $order_num; 
    
        Db::table('goods_transfers')->insert($transfersinsert);

        db::commit();

        return ['type'=>'success','code'=>200,'msg'=>'出货成功','data'=> [$out_no]];
    }




     //库位上下架商品库存
     public function location_change($params){
        $user_id = 0;
        if(isset($params['user_id'])){
            $user_id= $params['user_id'];
        }else{
            $user_data = DB::table('users')->where('token', '=', $params['token'])->select('Id', 'account')->first();
            if(empty($user_data)){
                return ['code'=>500,'msg'=>'该账号异常，无法操作'];
            }
            $user_id = $user_data->Id;
        }

        if(isset($params['order_no'])){
            $order_no = $params['order_no'];
        }

        if(isset($params['type'])){
            $type = $params['type'];
//            if ($type == 3){
//                return ['code'=>500,'msg'=>'调整上架功能已被禁用！！！'];
//            }
        }else{
            return ['code'=>500,'msg'=>'未获取到库位数据变动类型'];
        }

        if(isset($params['warehouse_id'])){
            $warehouse_id = $params['warehouse_id'];
        }else{
            return ['code'=>500,'msg'=>'未获取到仓库id'];
        }

        // if(isset($params['location_code'])){
        //     $location_code = $params['location_code'];
        // }else{
        //     return ['code'=>500,'msg'=>'未获取到库位编码'];
        // }
        $location_code = 'A01-001';

        if(isset($params['task_code']) && !empty($params['task_code'])){
            $boxData = DB::table('goods_transfers_box')->where('box_code',$params['task_code'])->select('id','onshelf_num','order_no','box_num','is_delete')->first();
            if(!empty($boxData)){
                if($boxData->is_delete==1){
                    return ['code'=>500,'msg'=>'此任务已取消，无法下架'];
                }
                $box_id = $boxData->id;
                $onshelf_num = $boxData->onshelf_num;
                $order_no = $boxData->order_no;
            }else{
                return ['code'=>500,'msg'=>'没有此中转箱/任务编码'];
            }

            if($type==1){
                // $detail_data =  DB::table('goods_transfers_box as a')->leftjoin('goods_transfers_box_detail as b','a.id','=','b.box_id')->where('a.box_code',$params['task_code'])->first();
                // if($detail_data->is_plan==0){
                //     return ['code'=>500,'msg'=>'该任务暂未分配国家'];
                // }

            }
        }else{
            if ($type != 5&&$type != 6){
                return ['code'=>500,'msg'=>'未获取到中转箱/任务编码'];
            }
        }


        $goods_transfers =  DB::table('goods_transfers')->where('order_no',$order_no)->select('in_house','out_house','id','is_push','type_detail','status','platform_id','shop_id')->first();
        if(!isset($params['platform_id'])){
            return ['code'=>500,'msg'=>'请选择国家'];
        }
        $platform_id = $params['platform_id'];


     

        // 上架：1，下架：2，调整上架：3，验货上架：5
        $checkType = [1, 2, 3];
        if (in_array($type, $checkType)){
            $type_detail = $goods_transfers->type_detail;
            $taskClassMdl = db::table('task_class')
                ->whereIn('fid', [42, 43, 44, 80])
                ->get();
            $taskClassMdl = json_decode(json_encode($taskClassMdl),true); 
            $taskClassIds = array_column($taskClassMdl, 'id');
            $tasks = DB::table('tasks')
                ->where('ext', 'like', "%{$order_no}%")
                ->where('is_deleted', 0)
                ->whereIn('class_id', $taskClassIds)
                ->select('desc','Id','class_id','ext')
                ->first();
            if(!empty($tasks)){
                if($goods_transfers->status<3){
                    return ['code'=>500,'msg'=>'该任务未审核通过，无法操作'];
                }
                if($tasks->Id==4){
                    if($type==1||$type==2){
                        return ['code'=>500,'msg'=>'该任务未已被拒绝，无法继续操作'];
                    }
                }
                $task_son = DB::table('tasks_son')->where('task_id', $tasks->Id)->select('state','Id','tasks_node_id')->first();
                if(!$task_son){
                    return ['code'=>500,'msg'=>'无此任务子节点'.$tasks->Id];
                }
                if($task_son->state==1){
                    $taskParam['Id'] = $task_son->Id;
                    $taskParam['tasks_node_id'] = $task_son->tasks_node_id;
                    $taskParam['task_id'] = $tasks->Id;
                    $taskParam['user_id'] = $user_id;
                    $taskModel = new Task();
                    $result = $taskModel->task_accept_model($taskParam);
                }

            }
            if($goods_transfers->is_push==3){
                return ['code'=>500,'msg'=>'订单已完成，无法继续操作'];
            }
            if($type!=3){
                if($goods_transfers->is_push==2){
                    //修改订单状态为操作中
                    $update =  DB::table('goods_transfers')->where('id',$goods_transfers->id)->update(['is_push'=>4]);
                    if(!$update){
                        return ['code'=>500,'msg'=>'修改状态失败'];
                    }
                }
                if($type==1){
                    if($type_detail==16){
                        if($warehouse_id!=$goods_transfers->out_house){
                            return ['code'=>500,'msg'=>'仓库选择错误'];
                        }
                    }else{
                        if($warehouse_id!=$goods_transfers->in_house){
                            return ['code'=>500,'msg'=>'仓库选择错误'];
                        }
                    }
                }elseif($type==2){
                    if($warehouse_id!=$goods_transfers->out_house){
                        return ['code'=>500,'msg'=>'仓库选择错误'];
                    }
                }
            }


        }

        $location = DB::table('cloudhouse_warehouse_location')->where('location_code',$location_code)->where('warehouse_id',$warehouse_id)->select('id','level')->first();
        if(!empty($location)){
            if($location->level!=3){
                return ['code'=>500,'msg'=>'此库位非三级库位，无法操作'];
            }else{
                $location_id = $location->id;
            }
        }else{
            return ['code'=>500,'msg'=>'没有此库位，请核对库位编码是否正确'];
        }

        $location_data = DB::table('cloudhouse_location_num')->where('location_id',$location_id)->select('custom_sku_id',
        'num','lock_num','platform_id')->get();

        $locationArr = array();
        $locationAll = array();

        if(!$location_data->isEmpty()){
            foreach ($location_data as $d){
                if(isset($locationAll[$d->custom_sku_id])){
                    $locationAll[$d->custom_sku_id] += $d->num;
                }else{
                    $locationAll[$d->custom_sku_id] = $d->num;
                }

                if($d->platform_id == $platform_id){
                    $locationArr[$d->custom_sku_id] = $d->num;
                }
            }
        }

        if($type==1){
            $custom_skuArr = array_column($params['data'],'id');
            $goods_transfers_detail = DB::table('goods_transfers_detail')->where('order_no',$order_no)->whereIn('custom_sku_id',$custom_skuArr)
                ->select('id','contract_no','custom_sku_id','receive_num','transfers_num')->get()->toArray();
            $contractArr = [];
            $transfersDetail = [];
            if(!empty($goods_transfers_detail)){
                foreach ($goods_transfers_detail as $gd){
                    if($gd->contract_no){
                        $contractArr[$gd->custom_sku_id] = $gd->contract_no;
                    }
                    $transfersDetail[$gd->custom_sku_id] = $gd;
                }
            }
            $inventoryArr = [];
            $self_custom_sku = DB::table('self_custom_sku')->whereIn('id',$custom_skuArr)->get()->toArray();
            if(!empty($self_custom_sku)){
                $self_custom_sku = json_decode(json_encode($self_custom_sku),true);
                foreach ($self_custom_sku as $sf){
                    $inventoryArr[$sf['id']] = $sf;
                }
            }
        }


        db::beginTransaction();
        try {
            $box_total = 0;
            $box_total2 = 0;
            foreach ($params['data'] as $v){
                // if($type==1){
                //     //如果是采购入库  则根据计划分配上架
                //     $plans = db::table('goods_transfers_plan')->where('box_code',$params['task_code'])->where('custom_sku_id',$v['id'])->get();
                //     $platform_id = 0;
                //     $goods_transfers_plan_id = 0;
                //     $goods_transfers_plan_num = 0;
                //     foreach ($plans as $v) {
                //         # code...
                //         if($platform_id==0){
                //             if(($v->plan_num - $v->num)>0){
                //                 $platform_id = $v->platform_id;
                //                 $goods_transfers_plan_id = $v->id;
                //                 $goods_transfers_plan_num = $v->num;
                //             }
                //         }

                //     }
                //     if($platform_id==0){
                //         return ['code'=>500,'msg'=>'预分配数量不足'];
                //     }
                //     //修改预分配
                //     db::table('goods_transfers_plan')->where('id',$goods_transfers_plan_id)->update(['num'=>$goods_transfers_plan_num]);
                // }
                $time = date('Y-m-d H:i:s');
                if($v['num']<1){
                    continue;
                }else{
                    if($type == 5){
                        $log['remark'] = '验货上架';
                    }elseif($type == 6){
                        $log['remark'] = '验货下架';
                    }else{
                        if($type == 3){
                            $log['remark'] = '调整上架';
                        }
                        $boxDetail = DB::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id']);
                        if($type==3){
                            $boxDetail = $boxDetail->select('box_num','shelf_num','id','location_ids')->get()->toArray();
                        }elseif($type==2){
                            $boxDetail = $boxDetail->where('location_ids',$location_id)->select('box_num','shelf_num','id','location_ids')->first();
                        }else{
                            $boxDetail = $boxDetail->select('box_num','shelf_num','id','location_ids')->first();
                        }

                        if(!empty($boxDetail)){
                            if($type==2) {
                                $shelf_num = $boxDetail->shelf_num;
                                if ($v['num']+$boxDetail->shelf_num > $boxDetail->box_num) {
                                    $exceed = $v['num'] - $boxDetail->box_num;
                                    throw new \Exception('操作失败，' . $v['custom_sku'] . '超出任务数量' . $exceed . '件');
                                }
                            }elseif($type==3) {
                                $shelf_num = 0;
                                $shelf_numArr = [];
                                foreach ($boxDetail as $bd){
                                    if($bd->shelf_num>0){
                                        $shelf_numArr[] = ['location_id'=>$bd->location_ids,'shelf_num'=>$bd->shelf_num];
                                    }
                                    $shelf_num += $bd->shelf_num;
                                }
                                $shelf_balance_num = $shelf_num - $v['num'];
                                if($shelf_balance_num<0){
                                    throw new \Exception('操作失败，'.$v['custom_sku'].'调整上架数量: '.$v['num'].' 大于已下架数量：'.$shelf_num);
                                }
                            }else{
                                $shelf_num = $boxDetail->shelf_num;
                                if ($v['num']+$shelf_num > $boxDetail->box_num) {
                                    $exceed = $v['num'] +$shelf_num - $boxDetail->box_num;
                                    throw new \Exception('操作失败，' . $v['custom_sku'] . '超出任务数量' . $exceed . '件');
                                }
                            }
                        }else{
                            throw new \Exception('操作失败，'.$box_id.'任务中没有'.$v['custom_sku'].'，请检查库位和箱码是否正确');
                        }
                    }

                    $log['spu'] = $v['spu'];
                    $log['spu_id'] = $this->GetSpuId($v['spu']);
                    $log['custom_sku_id'] = $v['id'];
                    $log['custom_sku'] = $v['custom_sku'];
                    $log['num'] = $v['num'];
                    $log['location_id'] = $location_id;
                    $log['time'] = $time;
                    $log['type'] = $type;
                    $log['order_no'] = $order_no ?? '';
                    $log['user_id'] = $user_id;
                    $log['platform_id'] = $platform_id;
                    if(isset($locationArr[$v['id']])){
                        if($type==1){
                            $balance = $v['num'] + $locationArr[$v['id']];
                            if(isset($locationAll[$v['id']])){
                                $balanceAll = $v['num'] + $locationAll[$v['id']];
                            }

                        }elseif ($type==2){
                            $balance = $locationArr[$v['id']] - $v['num'];
                            if(isset($locationAll[$v['id']])) {
                                $balanceAll = $locationAll[$v['id']] - $v['num'];
                            }
                            if($balance<0){
                                throw new \Exception('操作失败--'.$v['custom_sku'].'库位库存不足');
                            }
                        }elseif ($type == 3||$type == 5){
                            $balance = $v['num'] + $locationArr[$v['id']]; // 增加对应库位库存
                            if(isset($locationAll[$v['id']])) {
                                $balanceAll = $v['num'] + $locationAll[$v['id']];
                            }
                        }elseif ($type == 6){
                            $balance = $locationArr[$v['id']] - $v['num']; // 减去对应库位库存
                            if(isset($locationAll[$v['id']])) {
                                $balanceAll = $locationAll[$v['id']] - $v['num'];
                            }
                            if($balance<0){
                                throw new \Exception('操作失败--'.$v['custom_sku'].'库位库存不足');
                            }
                        }
                        $update = DB::table('cloudhouse_location_num')->where('location_id',$location_id)->where('platform_id',$platform_id)->where('custom_sku_id',$v['id'])->update(['num'=>$balance,'update_time'=>time()]);
                        if(!$update){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'操作失败--'.$v['custom_sku']];
                        }
                        $log['now_num'] = $balanceAll??0;
                        $log['now_platform_num'] = $balance;
                        $insertlog = DB::table('cloudhouse_location_log')->insert($log);
                        if(!$insertlog){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'新增日志失败--'.$v['custom_sku']];
                        }
                    }else{
                        if($type==2){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'当前库位没有此产品--'.$v['custom_sku']];
                        }
                        $insert['spu'] = $v['spu'];
                        $insert['spu_id'] = $this->GetSpuId($v['spu']);
                        $insert['custom_sku_id'] = $v['id'];
                        $insert['custom_sku'] = $v['custom_sku'];
                        $insert['num'] = $v['num'];
                        $insert['create_time'] = time();
                        $insert['location_id'] = $location_id;
                        $insert['platform_id'] = $platform_id;
                        $insertdata = DB::table('cloudhouse_location_num')->insert($insert);
                        if(!$insertdata){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'操作失败--'.$v['custom_sku']];
                        }

                        $log['now_num'] = $v['num'];
                        $log['now_platform_num'] = $v['num'];
                        $insertlog = DB::table('cloudhouse_location_log')->insert($log);
                        if(!$insertlog){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'新增日志失败--'.$v['custom_sku']];
                        }
                    }
                    if ($type == 3){
                        $box_total += $v['num'];
                        $this_now_num = $v['num'];
                        $i = 0;
                        do {
                            $this_now_num -= $shelf_numArr[$i]['shelf_num'];
                            if ($this_now_num > 0) {
                                db::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id'])
                                    ->where('location_ids', $shelf_numArr[$i]['location_id'])->update(['shelf_num'=>0]);
                            } else {
                                db::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id'])
                                    ->where('location_ids', $shelf_numArr[$i]['location_id'])
                                    ->update(['shelf_num'=>$shelf_numArr[$i]['shelf_num']-($this_now_num+$shelf_numArr[$i]['shelf_num'])]);
                            }
                            $i++;
                        } while ($this_now_num > 0);
                    }elseif($type==1||$type==2){

                        $update_boxDetail = DB::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$v['id']);
                        if($type==2){
                            $update_boxDetail = $update_boxDetail->where('location_ids',$location_id);
                        }

                        $updateArr['shelf_num'] = $v['num']+$shelf_num;
                        $update_boxDetail = $update_boxDetail->update($updateArr);
                        $box_total += $v['num'];
                        if(!$update_boxDetail){
                            db::rollback();// 回调
                            return ['code'=>500,'msg'=>'操作失败--'.$v['custom_sku']];
                        }

                        if($type==1){
                            //普通上架直接入库
                            if($type_detail==2){
                                if(!isset($contractArr[$v['id']])){
                                    $ts = json_encode( $contractArr);
                                    return ['code' => 500, 'msg' => '新增资产记录失败--无此库存sku合同号1-'.$v['id'].'-'.$ts];
                                }
                                $custom_sku_pirce = DB::table('cloudhouse_custom_sku')->where('custom_sku_id',$v['id'])
                                    ->where('contract_no',$contractArr[$v['id']])->select('price')->first();
                                if(empty($custom_sku_pirce)){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '未查询到合同单价--' . $v['custom_sku']];
                                }
                                $query['price'] = $custom_sku_pirce->price;
                            }else{
                                $query['price'] = $this->GetCloudHousePrice($warehouse_id, $v['id']);
                            }

                            $query['warehouse_id'] = $warehouse_id;
                            $query['custom_sku_id'] = $v['id'];

                            $query['num'] = $v['num'];
                            $query['user_id'] = $user_id;
                            $query['type'] = 2; //1为出2为入
                            $res = $this->UpCloudHousePrice($query);
                            if ($res['type'] != 'success') {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '新增资产记录失败--' . $v['custom_sku']];
                            }

                            $insertRecord['order_no'] = $order_no;
                            $insertRecord['spu'] = $v['spu'];
                            $insertRecord['spu_id'] = $this->GetSpuId($v['spu']);
                            $insertRecord['custom_sku_id'] = $v['id'];
                            $insertRecord['custom_sku'] = $v['custom_sku'];
                            $insertRecord['num'] = $v['num'];
                            $insertRecord['createtime'] = date('Y-m-d H:i:s');
                            $insertRecord['type'] = 2;
                            $insertRecord['user_id'] = $user_id;
                            $insertRecord['type_detail'] = $type_detail;
                            $insertRecord['warehouse_id'] = $warehouse_id;
                            $insertRecord['shop_id'] = $goods_transfers->shop_id;
                            $increase_num = $inventoryArr[$v['id']][self::WAREHOUSE[$warehouse_id]] + $v['num'];
                            $modify2Update[self::WAREHOUSE[$warehouse_id]] = $increase_num;
                            $modify2 = DB::table('self_custom_sku')->where('id', $v['id'])->update($modify2Update);

                            $insertRecord['price'] = $query['price'];
                            $insertRecord['now_inventory'] = $increase_num;
                            $insertRecord['now_total_price'] = $res['total_price'];
                            $insertIn = DB::table('cloudhouse_record')->insert($insertRecord);
                            if (!$insertIn) {
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '新增入库记录失败--' . $v['custom_sku']];
                            }
                            if(isset($transfersDetail[$v['id']])){
                                $updateDetailNum = $transfersDetail[$v['id']]->receive_num + $v['num'];
                                if($updateDetailNum>$transfersDetail[$v['id']]->transfers_num){
                                    db::rollback();// 回调
                                    return ['code' => 500, 'msg' => '入库数量超过清单数量--' . $v['custom_sku']];
                                }else{
                                    $goods_transfers_detail_one = DB::table('goods_transfers_detail')->where('id',$transfersDetail[$v['id']]->id)->first();
                                    $receive_num_arr = json_decode($goods_transfers_detail_one->receive_num_arr,true);

                                    $receive_num_arr[$platform_id]=$updateDetailNum;

                                    

                                    $updateThisDetail = DB::table('goods_transfers_detail')->where('id',$transfersDetail[$v['id']]->id)->update(['receive_num'=>$updateDetailNum,'receive_num_arr'=>json_encode($receive_num_arr)]);
                                    if(!$updateThisDetail){
                                        db::rollback();// 回调
                                        return ['code' => 500, 'msg' => '修改实际入库数量失败--' . $v['custom_sku']];
                                    }
                                }

                            }else{
                                db::rollback();// 回调
                                return ['code' => 500, 'msg' => '入库明细中无此sku数据--' . $v['custom_sku']];
                            }

                        }
                        //入库结束
                    }
                }
            }

            if ($type == 3){
                $onshelf_balance_num = $onshelf_num - $box_total;
                if($onshelf_balance_num==0){
                    DB::table('goods_transfers')->where('order_no',$order_no)->update(['is_push'=>2]);
                }
                DB::table('goods_transfers_box')->where('id',$box_id)->update(['onshelf_num'=>$onshelf_balance_num]);
            }elseif($type==1||$type==2){
                $receive_num = $onshelf_num+$box_total;
                if($receive_num == $boxData->box_num){
                    DB::table('goods_transfers_box')->where('id',$box_id)->update(['onshelf_num'=>$receive_num,'status'=>2]);
                }else{
                    DB::table('goods_transfers_box')->where('id',$box_id)->update(['onshelf_num'=>$receive_num]);
                }

            }
            db::commit();
            if(isset($type_detail)){
                if($type_detail==15){
                    return ['code'=>300,'msg'=>'操作成功','order_no'=>$order_no];
                }else{
                    return ['code'=>200,'msg'=>'操作成功'];
                }
            }else{
                return ['code'=>200,'msg'=>'操作成功'];
            }

        }catch (\Exception $e){
            db::rollback();
            return ['code'=>500,'msg'=>'操作失败--'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getCustomSkuLocationInventory($params)
    {

            if (!isset($params['warehouse_id']) || empty($params['warehouse_id'])){
                return ['data'=>'','msg'=>'仓库id参数错误'];
            }
            if (!isset($params['custom_sku_id']) || empty($params['custom_sku_id'])){
                return ['data'=>'','msg'=>'sku参数错误'];
            }
            if(isset($params['platform_id'])){
                if(!is_array($params['platform_id'])){
                    return ['data'=>'','msg'=>'平台参数错误，必须是数组'];
                }else{
                    $res = $this->inventoryPlatformDetail($params['custom_sku_id'],$params['warehouse_id'],$params['platform_id']);
                }
            }else{
                $res = $this->inventoryPlatformDetail($params['custom_sku_id'],$params['warehouse_id']);
            }

            return ['data'=>$res,'msg'=>'请求成功'];

    }

    //查询该平台该sku可分配库位与数量
    public function selectLocation($params){
        $custom_sku_id = $params['custom_sku_id'];

        $location_data = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')
            ->where('a.custom_sku_id',$custom_sku_id)
            ->where('b.warehouse_id',$params['out_house'])
            ->where('a.platform_id',$params['platform_id'])
            ->where('a.num', '>',0)
            ->select('a.*','b.location_code')
            ->get();

        $lock_inventory = $this->lock_inventory_d($custom_sku_id,$params['platform_id'],0,$params['out_house']);

      
        foreach ($location_data as $k=>$v){
            if(isset($lock_inventory[$custom_sku_id][$v->location_id][$params['platform_id']])){

                $location_data[$k]->instock_num = $v->num - $lock_inventory[$custom_sku_id][$v->location_id][$params['platform_id']];

            }else{
                $location_data[$k]->instock_num = $v->num;
            }
        }

        return $location_data;
    }

    //解锁清单上某个sku的库存
    public function unlockInventory($params){
//        return ['code'=>500,'msg'=>'解锁功能暂时禁用'];
        $location_data = $params['location_data'];
        $custom_sku_id = $params['custom_sku_id'];
        $box_code = $params['box_code'];

        $location_arr = [];
        foreach ($location_data as $l){
            $location_arr[] = $l['location_id'];
        }

        $lockData = DB::table('goods_transfers_box_detail as a')
            ->leftJoin('goods_transfers_box as b','a.box_id','=','b.id')
            ->where('b.box_code',$box_code)
            ->where('a.custom_sku_id',$custom_sku_id)
            ->whereIn('a.location_ids',$location_arr)
            ->select('a.id','a.box_num','b.box_num as box_total_num')
            ->get();

        $ids = [];
        $balance = 0;
        if(!$lockData->isEmpty()){
            $box_total_num = $lockData[0]->box_total_num;
            foreach ($lockData as $v){
                $ids[] = $v->id;
                $balance += $v->box_num;
            }
            $delete = DB::table('goods_transfers_box_detail')->whereIn('id',$ids)->delete();
            if($delete){
                $update = DB::table('goods_transfers_box')->where('box_code',$box_code)->update(['box_num'=>$box_total_num-$balance]);

                return ['code'=>200,'msg'=>'解锁成功'];
            }else{
                return ['code'=>500,'msg'=>'解锁失败'];
            }
        }else{
            return ['code'=>500,'msg'=>'未查询到锁定库存'];
        }
    }

    public function updateLocation($params){
        // return ['code'=>500,'msg'=>'更改库位功能暂时禁用'];
        $order_no = $params['order_no'];
        $location_data = $params['location_data'];
        $goods_transfers = DB::table('goods_transfers')->where('order_no',$order_no)->select('platform_id')->first();
        $box = DB::table('goods_transfers_box')->where('order_no',$order_no)->select('id','box_num','box_code','warehouse_id')->first();

        if(!empty($box)){

            $balance = 0;
            db::beginTransaction();
            foreach ($location_data as $v){
                $list = DB::table('goods_transfers_box_detail as a')
                    ->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')
                    ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no')
                    ->where('a.location_ids',$v['location_id'])
                    ->where('c.platform_id',$goods_transfers->platform_id)
                    ->where('a.custom_sku_id',$v['custom_sku_id'])
                    ->whereIn('c.is_push',[1,2,4])
                    ->whereIn('c.type_detail',$this->GetfieldTypeDetail())
                    ->select('a.box_num','a.shelf_num','c.order_no')
                    ->get()->toArray();
                $lock_num = 0;
                if(!empty($list)){
                    foreach ($list as $t){
                        $lock_num += $t->box_num - $t->shelf_num;
                    }
                }
               
                $location_num = DB::table('cloudhouse_location_num')->where('platform_id',$goods_transfers->platform_id)
                    ->where('custom_sku_id',$v['custom_sku_id'])->where('location_id', $v['location_id'])
                    ->select('num')->first();

                $instock_num = $location_num->num -$lock_num;
                if($instock_num<$v['num']){
                    db::rollback();// 回调
                    return ['code'=>500,'msg'=>'可用库存不足，请重新分配该库位数量'];
                }

                $insert['box_id'] = $box->id;
                $insert['custom_sku_id'] = $v['custom_sku_id'];
                $insert['custom_sku'] = $v['custom_sku'];
                $insert['location_ids'] = $v['location_id'];
                $insert['box_num'] = $v['num'];
                $balance += $v['num'];
                $add = DB::table('goods_transfers_box_detail')->insert($insert);
                if(!$add){
                    db::rollback();// 回调
                    return ['code'=>500,'msg'=>'新增分配库位数据失败'];
                }
            }

            $update = DB::table('goods_transfers_box')->where('id',$box->id)->update(['box_num'=>$box->box_num+$balance]);
            if(!$update){
                db::rollback();// 回调
                return ['code'=>500,'msg'=>'新增分配库位数据失败'];
            }
            db::commit();
            return ['code'=>200,'msg'=>'重新分配成功'];
        }else{
            return ['code'=>500,'msg'=>'没有查询到次中转任务'];
        }
    }

    /**
     * @Desc:更新实际到达时间和第三方编号
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/8/3 9:05
     */
    public function saveGoodsTransfersInfo($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给定出入库单标识！');
            }else{
                $goodsTransfersMdl = db::table('goods_transfers')
                    ->where('id', $params['id'])
                    ->first();
                if (empty($goodsTransfersMdl)){
                    throw new \Exception('未查询到出入库单数据！');
                }
            }
            $save = [
//                'delivery_time' => $params['delivery_time'] ?? '',
                'third_party_no' => $params['third_party_no'] ?? ''
            ];
            $update =  db::table('goods_transfers')
                ->where('id', $params['id'])
                ->update($save);
            if (empty($update)){
                throw new \Exception('无数据变化！');
            }

            return ['code' => 200, 'msg' => '更新成功！单号为:'.$goodsTransfersMdl->order_no];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '更新失败！原因:'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    /**
     * 平台间调整库存
     * @param $params
     * @param int $type 1:调公共平台库存 2:审批后调库存
     * @return array
     */
    public function adjustInventory($params, $type = 1)
    {
        $platformId        = $params['platform_id'];//调出平台
        $receivePlatformId = $params['receive_platform_id'];//调入平台
        $warehouseId       = $params['warehouse_id'];//仓库id
        $skuList           = array_column($params['sku_data'], 'num', 'custom_sku_id');
        $customSkuIds      = array_keys($skuList);

        $locationList  = [];

        foreach ($params['sku_data'] as $pv) {
            # code...
            $locationOne    = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->where('b.warehouse_id', $warehouseId)
            ->where('b.type', 1)
            ->where('a.platform_id', $platformId);
            if(isset($pv['location_id'])){
                $locationOne    = $locationOne->whereNotIn('a.location_id',$pv['location_id']);
            }

            $locationOne    = $locationOne
            ->where('a.custom_sku_id', $pv['custom_sku_id'])
            ->select('a.*')
            ->get();

            foreach ( $locationOne as $one) {
                # code...
                $locationList[] = $one;
            }


        }


        // $locationList      = DB::table('cloudhouse_location_num as a')
        //     ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
        //     ->where('b.warehouse_id', $warehouseId)
        //     ->where('b.type', 1)
        //     ->where('a.platform_id', $platformId)
        //     ->whereIn('a.custom_sku_id', $customSkuIds)
        //     ->get(['a.*']);
        // if ($locationList->isEmpty()) {
        //     return ['code' => 500, 'msg' => '没有这些产品的库存数据'];
        // }

        if(count($locationList)<1){
            return ['code' => 500, 'msg' => '没有这些产品的库存数据'];
        }

        $userIds = db::table('xt_role_user_join as a')
            ->leftJoin('users as b', 'a.user_id', '=', 'b.id')
            ->where('a.role_id', 1)
            ->where('b.state', 1)
            ->orWhere('b.Id', 638)
            ->pluck('a.user_id');
        if ($userIds->search($params['user_id']) == false && $platformId == 4){
            $customSkuMdl = db::table('self_custom_sku')
                ->where('spu_id', 244)
                ->get(['id', 'custom_sku'])
                ->keyBy('id');
            $checkIds = [];
            foreach ($customSkuMdl as $c){
                $checkIds[] = $c->id;
            }

            foreach ($skuList as $id => $num){
                if (in_array($id, $checkIds)){
                    $sku = $customSkuMdl[$id]->custom_sku ?? '';
                    return ['code' => 500, 'msg' => $sku.'非管理员不可调拨！'];
                }
            }
        }

        $inventory = [];//库存数量
        $skuGroup  = [];//按sku分列表
        foreach ($locationList as $v) {

            if (isset($inventory[$v->custom_sku_id])) {
                $inventory[$v->custom_sku_id] += $v->num;
            } else {
                $inventory[$v->custom_sku_id] = $v->num;
            }
            $skuGroup[$v->custom_sku_id][] = $v;

            //校验是否有同库位同库存正在操作
            $key = 'location_lock:'.$v->custom_sku_id.'-'. $platformId.'-'.$v->location_id;
            $lock = Redis::get($key);
            if($lock){
                return ['code' => 500, 'msg' => $key. '正在操作中，请等待20秒后再试'];
            }
            //锁10秒
            Redis::setex($key,10,1);

        }

        $lockList = DB::table('goods_transfers_box_detail as a')
            ->select('a.box_num', 'a.shelf_num', 'a.location_ids', 'a.custom_sku_id', 'c.platform_id')
            ->leftjoin('goods_transfers_box as b', 'a.box_id', '=', 'b.id')
            ->leftjoin('goods_transfers as c', 'b.order_no', '=', 'c.order_no')
            ->whereIn('c.type_detail', $this->GetfieldTypeDetail())
            ->whereIn('a.custom_sku_id', $customSkuIds)
            ->whereIn('c.is_push', [1, 2, 4])
            ->where('c.platform_id', $platformId)
            ->where('c.out_house',$warehouseId)
            ->get();
       
        $lockArr = [];//锁定库存
        $lockKeyByLcp =[];//以库位，sku,平台为主键
        foreach ($lockList as $v) {
            $balance = $v->box_num - $v->shelf_num;
            if ($balance > 0) {
                if (isset($lockArr[$v->custom_sku_id])) {
                    $lockArr[$v->custom_sku_id] += $balance;
                } else {
                    $lockArr[$v->custom_sku_id] = $balance;
                }

                $lcpKey = $v->location_ids . '_' . $v->custom_sku_id . '_' . $v->platform_id;
                if (isset($lockKeyByLcp[$lcpKey])) {
                    $lockKeyByLcp[$lcpKey] += $balance;
                } else {
                    $lockKeyByLcp[$lcpKey] = $balance;
                }
            }
        }



        $deficiencySku = [];//库存不足的sku
        foreach ($skuList as $sku => $num) {
            if (!isset($inventory[$sku])) {
                $deficiencySku[] = $sku;
                continue;
            }
            $lockNum = isset($lockArr[$sku]) ? $lockArr[$sku] : 0;
            if ($num > ($inventory[$sku] - $lockNum)) {
                $deficiencySku[] = $sku;
            }
        }


        if ($deficiencySku) {
            return ['code' => 500, 'msg' => json_encode($deficiencySku) . '库存不足'];

        }

        //非公共平台间调拔库存
        if ($type == 2) {
            $classIdArr = [1 => 32, 2 => 33];

            $customSkuArr = DB::table('self_custom_sku')
                ->select('id', 'custom_sku', 'old_custom_sku', 'spu_id')
                ->whereIn('id', $customSkuIds)
                ->get()
                ->keyBy('id');
            $spuIds = $customSkuArr->pluck('spu_id');
            $threeCateIds = DB::table('self_spu')->whereIn('id', $spuIds)->pluck('three_cate_id')->toArray();
            $threeCateIds = array_unique($threeCateIds);
            if (count($threeCateIds) > 1) {
                return ['code' => 500, 'msg' => '只能调同一产品类目'];
            }

            $userIds = DB::table('product_cate')
                ->where('type', 2)
                ->where('platform_id', $platformId)
                ->whereRaw("find_in_set({$threeCateIds[0]},`cate_ids`)")
                ->value('user_ids');
            $operateUserIds = [];
            $examineId = [];
            if (!is_null($userIds)){
                $operateUserIds = explode(',', $userIds);
                $examineId = array_map(function ($value){ return intval($value);}, $operateUserIds);
            }


            $id = DB::table('adjust_inventory_platform')->insertGetId([
                'warehouse_id'        => $params['warehouse_id'],
                'platform_id'         => $params['platform_id'],
                'receive_platform_id' => $params['receive_platform_id'],
                'user_id'             => $params['user_id'],
                'ext'                 => json_encode($params['sku_data']),
                'create_time'         => date('Y-m-d H:i:s')
            ]);

            return [
                'code' => 200,
                'msg'  => '',
                'data' => [
                    'class_id'        => $classIdArr[$warehouseId],
                    'operate_user_id' => $operateUserIds,
                    'fz_user_id'      => $params['user_id'],
                    'adjust_id'       => $id,
                    'adjust_link'     => '/platform_move_details?id=' . $id,
                    'ext'             => ['adjust_id', 'adjust_link'],
                    'examine_id'      => $examineId,
                ]
            ];
        }


        //遍历修改库存
        try {
            DB::begintransaction();

            // $skuKeyVal = $locationList->pluck('custom_sku', 'custom_sku_id');
            $insertLog = [];//插入操作记录

            foreach ($skuList as $sku => $num) {
                $skuLocation = $skuGroup[$sku];

                $balanceNum  = $num;

                //计算可用库存
                foreach ($skuLocation as $l) {
                    $lcpKey             = $l->location_id . '_' . $l->custom_sku_id . '_' . $l->platform_id;
                    $l->usableInventory = $l->num;//可用库存
                    if (isset($lockKeyByLcp[$lcpKey])) {
                        $l->usableInventory = $l->num - $lockKeyByLcp[$lcpKey];
                    }
                }
                //从大到小排序
                for($i = 0; $i < count($skuLocation)-1; $i++){
                    for ($j = 0; $j <count($skuLocation)-1-$i; $j++){
                        if($skuLocation[$j+1]->usableInventory > $skuLocation[$j]->usableInventory){
                            $temp = $skuLocation[$j];
                            $skuLocation[$j] = $skuLocation[$j + 1];
                            $skuLocation[$j + 1] = $temp;
                        }
                    }
                }


                foreach ($skuLocation as $l) {
                    $usableInventory = $l->usableInventory;//可用库存

                    if ($usableInventory <= 0) {
                        continue;
                    }

                    $insertTem = [
                        'warehouse_id'        => $warehouseId,
                        'custom_sku'          => db::table('self_custom_sku')->where('id',$sku)->first()->custom_sku,
                        'custom_sku_id'       => $sku,
                        'platform_id'         => $platformId,
                        'receive_platform_id' => $receivePlatformId,
                        'user_id'             => $params['user_id'],
                        'create_time'         => date('Y-m-d H:i:s'),
                    ];

                    if ( $usableInventory >= $balanceNum) {
                        $insertTem['num']         = $balanceNum;
                        $insertTem['location_id'] = $l->location_id;
                        $insertLog[]              = $insertTem;


                        DB::table('cloudhouse_location_num')->where('id', $l->id)->update([
                            'num'         => $l->num - $balanceNum,
                            'update_time' => time(),
                        ]);

                        $isExistInfo = DB::table('cloudhouse_location_num')
                            ->where('custom_sku_id', $l->custom_sku_id)
                            ->where('location_id', $l->location_id)
                            ->where('platform_id', $receivePlatformId)
                            ->first();

                        if ($isExistInfo) {

                            DB::table('cloudhouse_location_num')->where('id', $isExistInfo->id)->update([
                                'num' => $isExistInfo->num + $balanceNum,
                                'update_time' => time(),
                            ]);

                        } else {

                            //插入一条新的数据
                            DB::table('cloudhouse_location_num')->insert([
                                'custom_sku'    => $l->custom_sku,
                                'spu'           => $l->spu,
                                'custom_sku_id' => $l->custom_sku_id,
                                'spu_id'        => $l->spu_id,
                                'num'           => $balanceNum,
                                'lock_num'      => 0,
                                'location_id'   => $l->location_id,
                                'platform_id'   => $receivePlatformId,
                                'create_time'   => time(),
                                'update_time'   => time(),
                            ]);

                        }

                        break;
                    } else {
                        $balanceNum -= $usableInventory;

                        $insertTem['num']         = $usableInventory;
                        $insertTem['location_id'] = $l->location_id;
                        $insertLog[]              = $insertTem;


                        DB::table('cloudhouse_location_num')->where('id', $l->id)->update([
                            'num'         => $l->num - $usableInventory,
                            'update_time' => time(),
                        ]);

                        $isExistInfo = DB::table('cloudhouse_location_num')
                            ->where('custom_sku_id', $l->custom_sku_id)
                            ->where('location_id', $l->location_id)
                            ->where('platform_id', $receivePlatformId)
                            ->first();

                        if ($isExistInfo) {

                            DB::table('cloudhouse_location_num')->where('id', $isExistInfo->id)->update([
                                'num' => $isExistInfo->num + $usableInventory,
                                'update_time' => time(),
                            ]);

                        } else {

                            //插入一条新的数据
                            DB::table('cloudhouse_location_num')->insert([
                                'custom_sku'    => $l->custom_sku,
                                'spu'           => $l->spu,
                                'custom_sku_id' => $l->custom_sku_id,
                                'spu_id'        => $l->spu_id,
                                'num'           => $usableInventory,
                                'lock_num'      => 0,
                                'location_id'   => $l->location_id,
                                'platform_id'   => $receivePlatformId,
                                'create_time'   => time(),
                                'update_time'   => time(),
                            ]);

                        }
                    }
                }
            }
            //记录日志
            DB::table('adjust_inventory_log')->insert($insertLog);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollback();
            return ['code' => 500, 'msg' => $exception->getMessage()];
        }

        //同步到领星
        if ($receivePlatformId == 5 || $platformId == 5) {
            $lxParams = [
                'wid'  => $warehouseId, // 仓库id,喜马拉亚自己的id
                'type' => $receivePlatformId == 5 ? 1 : 11,
            ];
            $customSkuList = DB::table('self_custom_sku')->select('id', 'custom_sku')->whereIn('id', $customSkuIds)->get();
            foreach ($customSkuList as $value) {
                $lxParams['product_list'][] = [
                    'sku' => $value->custom_sku,
                    'good_num' => $skuList[$value->id],
                ];
            }
            $data = [
                'fun'    => $receivePlatformId == 5 ? 'addInStorageOrder' : 'addOutStorageOrder',
                'params' => $lxParams,
            ];

            //加入同步库存到翎星队列
            $job = new LingXingJob($data);
            $job->dispatch($data)->onQueue('ling_xing');
        }

        return ['code' => 200, 'msg' => '调拔成功'];
    }

    public function updateadjustInventoryDetail($params)
    {
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            if (!isset($params['adjust_id']) || empty($params['adjust_id'])){
                throw new \Exception('未给定库存调拨计划标识！');
            }

            $adjustMdl = db::table('adjust_inventory_platform')
                ->where('id', $params['adjust_id'])
                ->first();
            if (empty($adjustMdl)){
                throw new \Exception('库存调拨计划不存在！');
            }
            $taskMdl = db::table('tasks')
                ->where('is_deleted', 0)
                ->where('state', 1)
                ->whereIn('class_id', [32, 33])
                ->where('ext', 'like', '%"adjust_id":"'.$params['adjust_id'].'%')
                ->first();
            if (empty($taskMdl)){
                throw new \Exception('未查询到调库申请相关任务！');
            }
            $taskExamineMdl = db::table('tasks_examine')
                ->where('task_id', $taskMdl->Id)
                ->get();

            $taskExamineMdl = json_decode(json_encode($taskExamineMdl),true); 
            $taskExamineUserIds = array_column($taskExamineMdl, 'user_id');
            if ($params['user_id'] != $adjustMdl->user_id && !in_array($params['user_id'], $taskExamineUserIds)){
                throw new \Exception('调库申请任务申请人或任务审核人不可修改！');
            }
            $platformId = $adjustMdl->platform_id;
            $warehouseId = $adjustMdl->warehouse_id;
            $skuList = array_column($params['sku_data'], 'num', 'custom_sku_id');
            $customSkuIds = array_keys($skuList);
            $locationList = DB::table('cloudhouse_location_num as a')
                ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
                ->where('b.warehouse_id', $warehouseId)
                ->where('b.type', 1)
                ->where('a.platform_id', $platformId)
                ->whereIn('a.custom_sku_id', $customSkuIds)
                ->get(['a.*']);
            if ($locationList->isEmpty()) {
                throw new \Exception('没有这些产品的库存数据！');
            }

            $inventory = [];//库存数量
            $skuGroup  = [];//按sku分列表
            foreach ($locationList as $v) {

                if (isset($inventory[$v->custom_sku_id])) {
                    $inventory[$v->custom_sku_id] += $v->num;
                } else {
                    $inventory[$v->custom_sku_id] = $v->num;
                }
                $skuGroup[$v->custom_sku_id][] = $v;

                //校验是否有同库位同库存正在操作
                $key = 'location_lock:'.$v->custom_sku_id.'-'. $platformId.'-'.$v->location_id;
                $lock = Redis::get($key);
                if($lock){
                    throw new \Exception('正在操作中，请等待20秒后再试！');
                }
                //锁10秒
                Redis::setex($key,10,1);

            }

            $lockList = DB::table('goods_transfers_box_detail as a')
                ->select('a.box_num', 'a.shelf_num', 'a.location_ids', 'a.custom_sku_id', 'c.platform_id')
                ->leftjoin('goods_transfers_box as b', 'a.box_id', '=', 'b.id')
                ->leftjoin('goods_transfers as c', 'b.order_no', '=', 'c.order_no')
                ->whereIn('c.type_detail', $this->GetfieldTypeDetail())
                ->whereIn('a.custom_sku_id', $customSkuIds)
                ->whereIn('c.is_push', [1, 2, 4])
                ->where('c.platform_id', $platformId)
                ->where('c.out_house',$warehouseId)
                ->get();

            $lockArr = [];//锁定库存
            $lockKeyByLcp =[];//以库位，sku,平台为主键
            foreach ($lockList as $v) {
                $balance = $v->box_num - $v->shelf_num;
                if ($balance > 0) {
                    if (isset($lockArr[$v->custom_sku_id])) {
                        $lockArr[$v->custom_sku_id] += $balance;
                    } else {
                        $lockArr[$v->custom_sku_id] = $balance;
                    }

                    $lcpKey = $v->location_ids . '_' . $v->custom_sku_id . '_' . $v->platform_id;
                    if (isset($lockKeyByLcp[$lcpKey])) {
                        $lockKeyByLcp[$lcpKey] += $balance;
                    } else {
                        $lockKeyByLcp[$lcpKey] = $balance;
                    }
                }
            }



            $deficiencySku = [];//库存不足的sku
            foreach ($skuList as $sku => $num) {
                if (!isset($inventory[$sku])) {
                    $deficiencySku[] = $sku;
                    continue;
                }
                $lockNum = isset($lockArr[$sku]) ? $lockArr[$sku] : 0;
                if ($num > ($inventory[$sku] - $lockNum)) {
                    $deficiencySku[] = $sku;
                }
            }


            if ($deficiencySku) {
                throw new \Exception(json_encode($deficiencySku) . '库存不足！');
            }

            //非公共平台间调拔库存
            $customSkuArr = DB::table('self_custom_sku')
                ->select('id', 'custom_sku', 'old_custom_sku', 'spu_id')
                ->whereIn('id', $customSkuIds)
                ->get()
                ->keyBy('id');
            $spuIds = $customSkuArr->pluck('spu_id');
            $threeCateIds = DB::table('self_spu')->whereIn('id', $spuIds)->pluck('three_cate_id')->toArray();
            $threeCateIds = array_unique($threeCateIds);
            if (count($threeCateIds) > 1) {
                throw new \Exception('只能调同一产品类目！');
            }
            $update = db::table('adjust_inventory_platform')
                ->where('id', $params['adjust_id'])
                ->update([
                    'ext' => json_encode($params['sku_data']),
                    ]);
            if (empty($update)){
                throw new \Exception('修改失败！');
            }
            db::commit();
            return ['code' => 200, 'msg' => '修改成功！'];
        }catch (\Exception $e){
            DB::rollback();
            return ['code' => 500, 'msg' => '保存失败！原因：'.$e->getMessage().'，'.$e->getLine()];
        }
    }

    public function getSpuShipmentDeatilList($params)
    {
        $list = db::table('self_spu');

        if (isset($params['spu'])){
            $list = $list->where('spu', 'like', '%'.trim($params['spu']).'%')
                ->orwhere('old_spu', 'like', '%'.trim($params['spu']).'%');
        }

        if (isset($params['spu_id'])){
            $list = $list->where('id', $params['spu_id']);
        }

        if (isset($params['one_cate_id'])){
            $list = $list->whereIn('one_cate_id', $params['one_cate_id']);
        }

        if (isset($params['two_cate_id'])){
            $list = $list->whereIn('two_cate_id', $params['two_cate_id']);
        }

        if (isset($params['three_cate_id'])){
            $list = $list->whereIn('three_cate_id', $params['three_cate_id']);
        }

        $goodsTransfersMdl = db::table('goods_transfers_detail as a')
            ->leftJoin('goods_transfers as b', 'a.order_no', '=', 'b.order_no')
            ->whereIn('b.type_detail', [2, 6, 8, 9, 12,])
            ->where('b.is_push', '>', 1);

        $buhuoRequestMdl = db::table('amazon_buhuo_request as a')
            ->leftJoin('amazon_buhuo_detail as b', 'a.id', '=', 'b.request_id')
            ->where('a.request_status', '>', 3);

        $contractSkuMdl = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0);

        if (isset($params['created_at']) && is_array($params['created_at'])){
            $goodsTransfersMdl = $goodsTransfersMdl->whereBetween('b.push_time', $params['created_at']);
            $buhuoRequestMdl = $buhuoRequestMdl->whereBetween('a.request_time', $params['created_at']);
            $contractSkuMdl = $contractSkuMdl->whereBetween('b.create_time', $params['created_at']);
        }

        $count = $list->count();

        if ((isset($params['limit']) || isset($params['page'])) && !isset($params['post_type'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }
        $goodsTransfersMdl = $goodsTransfersMdl->get(['a.*', 'b.type_detail', 'b.platform_id']);
        $buhuoRequestMdl = $buhuoRequestMdl->get(['b.*', 'a.request_type']);
        $contractSkuMdl = $contractSkuMdl->get(['a.*']);
        $list = $list->get();

        $customSkuMdl = db::table('self_custom_sku')
            ->get();
        $customSkuList = [];
        foreach ($customSkuMdl as $c){
            if (isset($customSkuList[$c->spu_id])){
                $customSkuList[$c->spu_id]['tongan_inventory'] += $c->tongan_inventory;
                $customSkuList[$c->spu_id]['quanzhou_inventory'] += $c->quanzhou_inventory;
                $customSkuList[$c->spu_id]['cloud_num'] += $c->cloud_num;
                $customSkuList[$c->spu_id]['deposit_inventory'] += $c->deposit_inventory;
                $customSkuList[$c->spu_id]['direct_inventory'] += $c->direct_inventory;
            }else{
                $customSkuList[$c->spu_id] = [
                    'tongan_inventory' => $c->tongan_inventory,
                    'quanzhou_inventory' => $c->quanzhou_inventory,
                    'cloud_num' => $c->cloud_num,
                    'deposit_inventory' => $c->deposit_inventory,
                    'direct_inventory' => $c->direct_inventory,
                ];
            }
        }

        $amazonFactoryDirectList = [];
        foreach ($buhuoRequestMdl as $b){
            if ($b->request_type == 2){
                if (isset($amazonFactoryDirectList[$b->spu_id])){
                    $amazonFactoryDirectList[$b->spu_id] += $b->request_num;
                }else{
                    $amazonFactoryDirectList[$b->spu_id] = $b->request_num;
                }
            }
        }

        $contractNumList = [];
        $factoryNumList = [];
        foreach ($contractSkuMdl as $c){
            if (isset($contractNumList[$c->spu_id])){
                $contractNumList[$c->spu_id] += $c->num;
                $factoryNumList[$c->spu_id] += $c->num;
            }else{
                $contractNumList[$c->spu_id] = $c->num;
                $factoryNumList[$c->spu_id] = $c->num;
            }
        }
        $amazonRequstNumList = [];
        $pddRequestNumList = [];
        $otherPlatformNumList = [];
        $platformList = [];
        $platform = db::table('platform')
            ->get(['Id', 'name'])
            ->pluck('name', 'Id');
        foreach ($list as $v) {
            foreach ($platform as $k => $p) {
                $platformList[$v->id][$k] = 0;
            }
        }
        $inhouseNumList = [];
        foreach ($goodsTransfersMdl as $g){
            if ($g->type_detail == 2){
                if (isset($factoryNumList[$g->spu_id])){
                    $factoryNumList[$g->spu_id] -= $g->receive_num;
                }else{
                    $factoryNumList[$g->spu_id] = 0 - $g->receive_num;
                }
                if (isset($inhouseNumList[$g->spu_id])){
                    $inhouseNumList[$g->spu_id] += $g->receive_num;
                }else{
                    $inhouseNumList[$g->spu_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 6){
                if (isset($amazonRequstNumList[$g->spu_id])){
                    $amazonRequstNumList[$g->spu_id] += $g->receive_num;
                }else{
                    $amazonRequstNumList[$g->spu_id] = $g->receive_num;
                }
                if (isset($platformList[$g->spu_id][$g->platform_id])){
                    $platformList[$g->spu_id][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$g->spu_id][$g->platform_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 8){
                if ($g->platform_id == 12){
                    if (isset($pddRequestNumList[$g->spu_id])){
                        $pddRequestNumList[$g->spu_id] += $g->receive_num;
                    }else{
                        $pddRequestNumList[$g->spu_id] = $g->receive_num;
                    }
                }
                if ($g->platform_id == 5){
                    if (isset($amazonRequstNumList[$g->spu_id])){
                        $amazonRequstNumList[$g->spu_id] += $g->receive_num;
                    }else{
                        $amazonRequstNumList[$g->spu_id] = $g->receive_num;
                    }
                }
                if (!in_array($g->platform_id, [5,12])){
                    if (isset($otherPlatformNumList[$g->spu_id])){
                        $otherPlatformNumList[$g->spu_id] += $g->receive_num;
                    }else{
                        $otherPlatformNumList[$g->spu_id] = $g->receive_num;
                    }
                }
                if (isset($platformList[$g->spu_id][$g->platform_id])){
                    $platformList[$g->spu_id][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$g->spu_id][$g->platform_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 9){
                if (isset($factoryNumList[$g->spu_id])){
                    $factoryNumList[$g->spu_id] += $g->receive_num;
                }else{
                    $factoryNumList[$g->spu_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 12){
                if ($g->platform_id == 12){
                    if (isset($pddRequestNumList[$g->spu_id])){
                        $pddRequestNumList[$g->spu_id] += $g->receive_num;
                    }else{
                        $pddRequestNumList[$g->spu_id] = $g->receive_num;
                    }
                }
                if ($g->platform_id == 5){
                    if (isset($amazonRequstNumList[$g->spu_id])){
                        $amazonRequstNumList[$g->spu_id] += $g->receive_num;
                    }else{
                        $amazonRequstNumList[$g->spu_id] = $g->receive_num;
                    }
                }
                if (!in_array($g->platform_id, [5,12])){
                    if (isset($otherPlatformNumList[$g->spu_id])){
                        $otherPlatformNumList[$g->spu_id] += $g->receive_num;
                    }else{
                        $otherPlatformNumList[$g->spu_id] = $g->receive_num;
                    }
                }
                if (isset($platformList[$g->spu_id][$g->platform_id])){
                    $platformList[$g->spu_id][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$g->spu_id][$g->platform_id] = $g->receive_num;
                }
            }
        }
        foreach ($list as $v){
            $v->img = $this->GetSpuImg($v->spu) ?? '';
            if (isset($platformList[$v->id])){
                foreach ($platformList[$v->id] as $_k => $_v){
                    if ($_v <= 0){
                        $platformList[$v->id][$_k] = '';
                    }
                }
            }
            $v->platform_num = $platformList[$v->id] ?? [];
            $v->contract_num = isset($contractNumList[$v->id]) && $contractNumList[$v->id] > 0 ? $contractNumList[$v->id] : '';
            $v->amazon_request_num = isset($amazonRequstNumList[$v->id]) && $amazonRequstNumList[$v->id] > 0 ? $amazonRequstNumList[$v->id] : '';
            $v->pdd_request_num = isset($pddRequestNumList[$v->id]) && $pddRequestNumList[$v->id] > 0 ? $pddRequestNumList[$v->id] : '';
            $v->factory_num = isset($factoryNumList[$v->id]) && $factoryNumList[$v->id] > 0 ? $factoryNumList[$v->id] : '';
            $v->one_cate_name = $this->GetCategory($v->one_cate_id)['name'] ?? '';
            $v->two_cate_name = $this->GetCategory($v->two_cate_id)['name'] ?? '';
            $v->three_cate_name = $this->GetCategory($v->three_cate_id)['name'] ?? '';
            $v->amazon_factory_request_num = isset($amazonFactoryDirectList[$v->id]) && $amazonFactoryDirectList[$v->id] > 0 ? $amazonFactoryDirectList[$v->id] : '';
            $v->pdd_factory_request_num = '';
            $v->in_house_num = isset($inhouseNumList[$v->id]) && $inhouseNumList[$v->id] > 0 ? $inhouseNumList[$v->id] : '';
            $v->other_platform_num = isset($otherPlatformNumList[$v->id]) && $otherPlatformNumList[$v->id] > 0 ? $otherPlatformNumList[$v->id] : '';
            $v->tongan_inventory = isset($customSkuList[$v->id]['tongan_inventory']) && $customSkuList[$v->id]['tongan_inventory'] > 0 ? $customSkuList[$v->id]['tongan_inventory'] : '';
            $v->quanzhou_inventory = isset($customSkuList[$v->id]['quanzhou_inventory']) && $customSkuList[$v->id]['quanzhou_inventory'] > 0 ? $customSkuList[$v->id]['quanzhou_inventory'] : '';
            $v->cloud_num = isset($customSkuList[$v->id]['cloud_num']) && $customSkuList[$v->id]['cloud_num'] > 0 ? $customSkuList[$v->id]['cloud_num'] : '';
            $v->deposit_inventory = isset($customSkuList[$v->id]['deposit_inventory']) && $customSkuList[$v->id]['deposit_inventory'] > 0 ? $customSkuList[$v->id]['deposit_inventory'] : '';
            $v->direct_inventory = isset($customSkuList[$v->id]['direct_inventory']) && $customSkuList[$v->id]['direct_inventory'] > 0 ? $customSkuList[$v->id]['direct_inventory'] : '';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'platform_list' => $platform, 'list' => $list, ]];
    }

    public function getSpuColorShipmentDeatilList($params)
    {
        $list = db::table('self_spu as a')
            ->leftJoin('self_spu_color as b', 'a.base_spu_id', '=', 'b.base_spu_id')
            ->leftJoin('self_color_size as c', 'b.color_id', '=', 'c.id');

        if (isset($params['spu'])){
            $list = $list->where('a.spu', 'like', '%'.trim($params['spu']).'%')
                ->orwhere('a.old_spu', 'like', '%'.trim($params['spu']).'%');
        }

        if (isset($params['spu_id'])){
            $list = $list->where('a.id', $params['spu_id']);
        }

        if (isset($params['color_id'])){
            $list = $list->where('b.color_id', $params['color_id']);
        }

        if (isset($params['one_cate_id'])){
            $list = $list->whereIn('a.one_cate_id', $params['one_cate_id']);
        }

        if (isset($params['two_cate_id'])){
            $list = $list->whereIn('a.two_cate_id', $params['two_cate_id']);
        }

        if (isset($params['three_cate_id'])){
            $list = $list->whereIn('a.three_cate_id', $params['three_cate_id']);
        }

        $goodsTransfersMdl = db::table('goods_transfers_detail as a')
            ->leftJoin('goods_transfers as b', 'a.order_no', '=', 'b.order_no')
            ->leftJoin('self_custom_sku as c', 'a.custom_sku_id', '=', 'c.id')
            ->whereIn('b.type_detail', [2, 6, 8, 9, 12,])
            ->where('b.is_push', '>', 1);

        $buhuoRequestMdl = db::table('amazon_buhuo_request as a')
            ->leftJoin('amazon_buhuo_detail as b', 'a.id', '=', 'b.request_id')
            ->leftJoin('self_custom_sku as c', 'b.custom_sku_id', '=', 'c.id')
            ->where('a.request_status', '>', 3);

        $contractSkuMdl = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->leftJoin('self_custom_sku as c', 'a.custom_sku_id', '=', 'c.id')
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0);

        if (isset($params['created_at']) && is_array($params['created_at'])){
            $goodsTransfersMdl = $goodsTransfersMdl->whereBetween('b.push_time', $params['created_at']);
            $buhuoRequestMdl = $buhuoRequestMdl->whereBetween('a.request_time', $params['created_at']);
            $contractSkuMdl = $contractSkuMdl->whereBetween('b.create_time', $params['created_at']);
        }

        $count = $list->count();

        if ((isset($params['limit']) || isset($params['page'])) && !isset($params['post_type'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }
        $goodsTransfersMdl = $goodsTransfersMdl->get(['a.*', 'b.type_detail', 'b.platform_id', 'c.color_id']);
        $buhuoRequestMdl = $buhuoRequestMdl->get(['b.*', 'a.request_type', 'c.color_id']);
        $contractSkuMdl = $contractSkuMdl->get(['a.*', 'c.color_id']);
        $list = $list->get(['a.*', 'b.img', 'b.color_id', 'c.name as color_name', 'c.identifying as color_identifying']);

        $customSkuMdl = db::table('self_custom_sku')
            ->get();
        $customSkuList = [];
        foreach ($customSkuMdl as $c){
            if (isset($customSkuList[$c->spu_id])){
                $customSkuList[$c->spu_id]['tongan_inventory'] += $c->tongan_inventory;
                $customSkuList[$c->spu_id]['quanzhou_inventory'] += $c->quanzhou_inventory;
                $customSkuList[$c->spu_id]['cloud_num'] += $c->cloud_num;
                $customSkuList[$c->spu_id]['deposit_inventory'] += $c->deposit_inventory;
                $customSkuList[$c->spu_id]['direct_inventory'] += $c->direct_inventory;
            }else{
                $customSkuList[$c->spu_id] = [
                    'tongan_inventory' => $c->tongan_inventory,
                    'quanzhou_inventory' => $c->quanzhou_inventory,
                    'cloud_num' => $c->cloud_num,
                    'deposit_inventory' => $c->deposit_inventory,
                    'direct_inventory' => $c->direct_inventory,
                ];
            }
        }

        $amazonFactoryDirectList = [];
        foreach ($buhuoRequestMdl as $b){
            if ($b->request_type == 2){
                $key = $b->spu_id.'-'.$b->color_id;
                if (isset($amazonFactoryDirectList[$key])){
                    $amazonFactoryDirectList[$key] += $b->request_num;
                }else{
                    $amazonFactoryDirectList[$key] = $b->request_num;
                }
            }
        }

        $contractNumList = [];
        $factoryNumList = [];
        foreach ($contractSkuMdl as $c){
            $key = $c->spu_id.'-'.$c->color_id;
            if (isset($contractNumList[$key])){
                $contractNumList[$key] += $c->num;
                $factoryNumList[$key] += $c->num;
            }else{
                $contractNumList[$key] = $c->num;
                $factoryNumList[$key] = $c->num;
            }
        }
        $amazonRequstNumList = [];
        $pddRequestNumList = [];
        $otherPlatformNumList = [];
        $platformList = [];
        $platform = db::table('platform')
            ->get(['Id', 'name'])
            ->pluck('name', 'Id');
        foreach ($list as $v) {
            foreach ($platform as $k => $p) {
                $platformList[$v->id][$k] = 0;
            }
        }
        $inhouseNumList = [];
        foreach ($goodsTransfersMdl as $g){
            $key = $g->spu_id.'-'.$g->color_id;
            if ($g->type_detail == 2){
                if (isset($factoryNumList[$key])){
                    $factoryNumList[$key] -= $g->receive_num;
                }else{
                    $factoryNumList[$key] = 0 - $g->receive_num;
                }
                if (isset($inhouseNumList[$key])){
                    $inhouseNumList[$key] += $g->receive_num;
                }else{
                    $inhouseNumList[$key] = $g->receive_num;
                }
            }
            if ($g->type_detail == 6){
                if (isset($amazonRequstNumList[$g->spu_id])){
                    $amazonRequstNumList[$key] += $g->receive_num;
                }else{
                    $amazonRequstNumList[$key] = $g->receive_num;
                }
                if (isset($platformList[$key][$g->platform_id])){
                    $platformList[$key][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$key][$g->platform_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 8){
                if ($g->platform_id == 12){
                    if (isset($pddRequestNumList[$key])){
                        $pddRequestNumList[$key] += $g->receive_num;
                    }else{
                        $pddRequestNumList[$key] = $g->receive_num;
                    }
                }
                if ($g->platform_id == 5){
                    if (isset($amazonRequstNumList[$key])){
                        $amazonRequstNumList[$key] += $g->receive_num;
                    }else{
                        $amazonRequstNumList[$key] = $g->receive_num;
                    }
                }
                if (!in_array($g->platform_id, [5,12])){
                    if (isset($otherPlatformNumList[$key])){
                        $otherPlatformNumList[$key] += $g->receive_num;
                    }else{
                        $otherPlatformNumList[$key] = $g->receive_num;
                    }
                }
                if (isset($platformList[$key][$g->platform_id])){
                    $platformList[$key][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$key][$g->platform_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 9){
                if (isset($factoryNumList[$key])){
                    $factoryNumList[$key] += $g->receive_num;
                }else{
                    $factoryNumList[$key] = $g->receive_num;
                }
            }
            if ($g->type_detail == 12){
                if ($g->platform_id == 12){
                    if (isset($pddRequestNumList[$key])){
                        $pddRequestNumList[$key] += $g->receive_num;
                    }else{
                        $pddRequestNumList[$key] = $g->receive_num;
                    }
                }
                if ($g->platform_id == 5){
                    if (isset($amazonRequstNumList[$key])){
                        $amazonRequstNumList[$key] += $g->receive_num;
                    }else{
                        $amazonRequstNumList[$key] = $g->receive_num;
                    }
                }
                if (!in_array($g->platform_id, [5,12])){
                    if (isset($otherPlatformNumList[$key])){
                        $otherPlatformNumList[$key] += $g->receive_num;
                    }else{
                        $otherPlatformNumList[$key] = $g->receive_num;
                    }
                }
                if (isset($platformList[$key][$g->platform_id])){
                    $platformList[$key][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$key][$g->platform_id] = $g->receive_num;
                }
            }
        }
        foreach ($list as $v){
            $key = $v->id.'-'.$v->color_id;
            $v->color_name = $v->color_name.'/'.$v->color_identifying;
            if (isset($platformList[$key])){
                foreach ($platformList[$key] as $_k => $_v){
                    if ($_v <= 0){
                        $platformList[$key][$_k] = '';
                    }
                }
            }
            $v->platform_num = $platformList[$key] ?? [];
            $v->contract_num = isset($contractNumList[$key]) && $contractNumList[$key] > 0 ? $contractNumList[$key] : '';
            $v->amazon_request_num = isset($amazonRequstNumList[$key]) && $amazonRequstNumList[$key] > 0 ? $amazonRequstNumList[$key] : '';
            $v->pdd_request_num = isset($pddRequestNumList[$key]) && $pddRequestNumList[$key] > 0 ? $pddRequestNumList[$key] : '';
            $v->factory_num = isset($factoryNumList[$key]) && $factoryNumList[$key] > 0 ? $factoryNumList[$key] : '';
            $v->one_cate_name = $this->GetCategory($v->one_cate_id)['name'] ?? '';
            $v->two_cate_name = $this->GetCategory($v->two_cate_id)['name'] ?? '';
            $v->three_cate_name = $this->GetCategory($v->three_cate_id)['name'] ?? '';
            $v->amazon_factory_request_num = isset($amazonFactoryDirectList[$key]) && $amazonFactoryDirectList[$key] > 0 ? $amazonFactoryDirectList[$key] : '';
            $v->pdd_factory_request_num = '';
            $v->in_house_num = isset($inhouseNumList[$key]) && $inhouseNumList[$key] > 0 ? $inhouseNumList[$key] : '';
            $v->other_platform_num = isset($otherPlatformNumList[$key]) && $otherPlatformNumList[$key] > 0 ? $otherPlatformNumList[$key] : '';
            $v->tongan_inventory = isset($customSkuList[$key]['tongan_inventory']) && $customSkuList[$key]['tongan_inventory'] > 0 ? $customSkuList[$key]['tongan_inventory'] : '';
            $v->quanzhou_inventory = isset($customSkuList[$key]['quanzhou_inventory']) && $customSkuList[$key]['quanzhou_inventory'] > 0 ? $customSkuList[$key]['quanzhou_inventory'] : '';
            $v->cloud_num = isset($customSkuList[$key]['cloud_num']) && $customSkuList[$key]['cloud_num'] > 0 ? $customSkuList[$key]['cloud_num'] : '';
            $v->deposit_inventory = isset($customSkuList[$key]['deposit_inventory']) && $customSkuList[$key]['deposit_inventory'] > 0 ? $customSkuList[$key]['deposit_inventory'] : '';
            $v->direct_inventory = isset($customSkuList[$key]['direct_inventory']) && $customSkuList[$key]['direct_inventory'] > 0 ? $customSkuList[$key]['direct_inventory'] : '';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'platform_list' => $platform, 'list' => $list, ]];
    }

    public function getCustomSkuShipmentDeatilList($params)
    {
        $list = db::table('self_custom_sku as a')
            ->leftJoin('self_spu as b', 'a.spu_id', '=', 'b.id');

        if (isset($params['spu'])){
            $list = $list->where('b.spu', 'like', '%'.trim($params['spu']).'%')
                ->orwhere('b.old_spu', 'like', '%'.trim($params['spu']).'%');
        }

        if (isset($params['custom_sku'])){
            $list = $list->where('a.custom_sku', 'like', '%'.trim($params['custom_sku']).'%')
                ->orwhere('a.old_custom_sku', 'like', '%'.trim($params['custom_sku']).'%');
        }

        if (isset($params['spu_id'])){
            $list = $list->where('b.id', $params['spu_id']);
        }

        if (isset($params['color_id'])){
            $list = $list->where('a.color_id', $params['color_id']);
        }

        if (isset($params['one_cate_id'])){
            $list = $list->whereIn('b.one_cate_id', $params['one_cate_id']);
        }

        if (isset($params['two_cate_id'])){
            $list = $list->whereIn('b.two_cate_id', $params['two_cate_id']);
        }

        if (isset($params['three_cate_id'])){
            $list = $list->whereIn('b.three_cate_id', $params['three_cate_id']);
        }

        $goodsTransfersMdl = db::table('goods_transfers_detail as a')
            ->leftJoin('goods_transfers as b', 'a.order_no', '=', 'b.order_no')
            ->whereIn('b.type_detail', [2, 6, 8, 9, 12,])
            ->where('b.is_push', '>', 1);

        $buhuoRequestMdl = db::table('amazon_buhuo_request as a')
            ->leftJoin('amazon_buhuo_detail as b', 'a.id', '=', 'b.request_id')
            ->where('a.request_status', '>', 3);

        $contractSkuMdl = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0);

        if (isset($params['created_at']) && is_array($params['created_at'])){
            $goodsTransfersMdl = $goodsTransfersMdl->whereBetween('b.push_time', $params['created_at']);
            $buhuoRequestMdl = $buhuoRequestMdl->whereBetween('a.request_time', $params['created_at']);
            $contractSkuMdl = $contractSkuMdl->whereBetween('b.create_time', $params['created_at']);
        }

        $count = $list->count();

        if ((isset($params['limit']) || isset($params['page'])) && !isset($params['post_type'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)
                ->offset($offsetNum);
        }
        $goodsTransfersMdl = $goodsTransfersMdl->get(['a.*', 'b.type_detail', 'b.platform_id']);
        $buhuoRequestMdl = $buhuoRequestMdl->get(['b.*', 'a.request_type']);
        $contractSkuMdl = $contractSkuMdl->get(['a.*']);
        $list = $list->get(['a.*', 'b.one_cate_id', 'b.two_cate_id', 'b.three_cate_id', 'b.spu', 'b.old_spu']);


        $amazonFactoryDirectList = [];
        foreach ($buhuoRequestMdl as $b){
            if ($b->request_type == 2){
                if (isset($amazonFactoryDirectList[$b->custom_sku_id])){
                    $amazonFactoryDirectList[$b->custom_sku_id] += $b->request_num;
                }else{
                    $amazonFactoryDirectList[$b->custom_sku_id] = $b->request_num;
                }
            }
        }

        $contractNumList = [];
        $factoryNumList = [];
        foreach ($contractSkuMdl as $c){
            if (isset($contractNumList[$c->custom_sku_id])){
                $contractNumList[$c->custom_sku_id] += $c->num;
                $factoryNumList[$c->custom_sku_id] += $c->num;
            }else{
                $contractNumList[$c->custom_sku_id] = $c->num;
                $factoryNumList[$c->custom_sku_id] = $c->num;
            }
        }
        $amazonRequstNumList = [];
        $pddRequestNumList = [];
        $otherPlatformNumList = [];
        $platformList = [];
        $platform = db::table('platform')
            ->get(['Id', 'name'])
            ->pluck('name', 'Id');
        foreach ($list as $v) {
            foreach ($platform as $k => $p) {
                $platformList[$v->id][$k] = 0;
            }
        }
        $inhouseNumList = [];
        foreach ($goodsTransfersMdl as $g){
            if ($g->type_detail == 2){
                if (isset($factoryNumList[$g->custom_sku_id])){
                    $factoryNumList[$g->custom_sku_id] -= $g->receive_num;
                }else{
                    $factoryNumList[$g->custom_sku_id] = 0 - $g->receive_num;
                }
                if (isset($inhouseNumList[$g->custom_sku_id])){
                    $inhouseNumList[$g->custom_sku_id] += $g->receive_num;
                }else{
                    $inhouseNumList[$g->custom_sku_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 6){
                if (isset($amazonRequstNumList[$g->custom_sku_id])){
                    $amazonRequstNumList[$g->custom_sku_id] += $g->receive_num;
                }else{
                    $amazonRequstNumList[$g->custom_sku_id] = $g->receive_num;
                }
                if (isset($platformList[$g->custom_sku_id][$g->platform_id])){
                    $platformList[$g->custom_sku_id][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$g->custom_sku_id][$g->platform_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 8){
                if ($g->platform_id == 12){
                    if (isset($pddRequestNumList[$g->custom_sku_id])){
                        $pddRequestNumList[$g->custom_sku_id] += $g->receive_num;
                    }else{
                        $pddRequestNumList[$g->custom_sku_id] = $g->receive_num;
                    }
                }
                if ($g->platform_id == 5){
                    if (isset($amazonRequstNumList[$g->custom_sku_id])){
                        $amazonRequstNumList[$g->custom_sku_id] += $g->receive_num;
                    }else{
                        $amazonRequstNumList[$g->custom_sku_id] = $g->receive_num;
                    }
                }
                if (!in_array($g->platform_id, [5,12])){
                    if (isset($otherPlatformNumList[$g->custom_sku_id])){
                        $otherPlatformNumList[$g->custom_sku_id] += $g->receive_num;
                    }else{
                        $otherPlatformNumList[$g->custom_sku_id] = $g->receive_num;
                    }
                }
                if (isset($platformList[$g->custom_sku_id][$g->platform_id])){
                    $platformList[$g->custom_sku_id][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$g->custom_sku_id][$g->platform_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 9){
                if (isset($factoryNumList[$g->custom_sku_id])){
                    $factoryNumList[$g->custom_sku_id] += $g->receive_num;
                }else{
                    $factoryNumList[$g->custom_sku_id] = $g->receive_num;
                }
            }
            if ($g->type_detail == 12){
                if ($g->platform_id == 12){
                    if (isset($pddRequestNumList[$g->custom_sku_id])){
                        $pddRequestNumList[$g->custom_sku_id] += $g->receive_num;
                    }else{
                        $pddRequestNumList[$g->custom_sku_id] = $g->receive_num;
                    }
                }
                if ($g->platform_id == 5){
                    if (isset($amazonRequstNumList[$g->custom_sku_id])){
                        $amazonRequstNumList[$g->custom_sku_id] += $g->receive_num;
                    }else{
                        $amazonRequstNumList[$g->custom_sku_id] = $g->receive_num;
                    }
                }
                if (!in_array($g->platform_id, [5,12])){
                    if (isset($otherPlatformNumList[$g->custom_sku_id])){
                        $otherPlatformNumList[$g->custom_sku_id] += $g->receive_num;
                    }else{
                        $otherPlatformNumList[$g->custom_sku_id] = $g->receive_num;
                    }
                }
                if (isset($platformList[$g->custom_sku_id][$g->platform_id])){
                    $platformList[$g->custom_sku_id][$g->platform_id] += $g->receive_num;
                }else{
                    $platformList[$g->custom_sku_id][$g->platform_id] = $g->receive_num;
                }
            }
        }
        foreach ($list as $v){
            $v->img = $this->GetCustomskuImg($v->custom_sku) ?? '';
            $v->color_name = $v->color_name.'/'.$v->color;
            if (isset($platformList[$v->id])){
                foreach ($platformList[$v->id] as $_k => $_v){
                    if ($_v <= 0){
                        $platformList[$v->id][$_k] = '';
                    }
                }
            }
            $v->platform_num = $platformList[$v->id] ?? [];
            $v->contract_num = isset($contractNumList[$v->id]) && $contractNumList[$v->id] > 0 ? $contractNumList[$v->id] : '';
            $v->amazon_request_num = isset($amazonRequstNumList[$v->id]) && $amazonRequstNumList[$v->id] > 0 ? $amazonRequstNumList[$v->id] : '';
            $v->pdd_request_num = isset($pddRequestNumList[$v->id]) && $pddRequestNumList[$v->id] > 0 ? $pddRequestNumList[$v->id] : '';
            $v->factory_num = isset($factoryNumList[$v->id]) && $factoryNumList[$v->id] > 0 ? $factoryNumList[$v->id] : '';
            $v->one_cate_name = $this->GetCategory($v->one_cate_id)['name'] ?? '';
            $v->two_cate_name = $this->GetCategory($v->two_cate_id)['name'] ?? '';
            $v->three_cate_name = $this->GetCategory($v->three_cate_id)['name'] ?? '';
            $v->amazon_factory_request_num = isset($amazonFactoryDirectList[$v->id]) && $amazonFactoryDirectList[$v->id] > 0 ? $amazonFactoryDirectList[$v->id] : '';
            $v->pdd_factory_request_num = '';
            $v->in_house_num = isset($inhouseNumList[$v->id]) && $inhouseNumList[$v->id] > 0 ? $inhouseNumList[$v->id] : '';
            $v->other_platform_num = isset($otherPlatformNumList[$v->id]) && $otherPlatformNumList[$v->id] > 0 ? $otherPlatformNumList[$v->id] : '';
            $v->tongan_inventory = $v->tongan_inventory > 0 ? $v->tongan_inventory : '';
            $v->quanzhou_inventory = $v->quanzhou_inventory > 0 ? $v->quanzhou_inventory : '';
            $v->cloud_num = $v->cloud_num > 0 ? $v->cloud_num : '';
            $v->deposit_inventory = $v->deposit_inventory > 0 ? $v->deposit_inventory : '';
            $v->direct_inventory = $v->direct_inventory > 0 ? $v->direct_inventory : '';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'platform_list' => $platform, 'list' => $list, ]];
    }

    public function saveCustomSkuInventoryMonth($params)
    {
        try {
            $job = new \App\Http\Controllers\Jobs\SaveCustomSkuMonthInventoryController;
            $job::runJob([]);
            return ['code' => 200, 'msg' => '加入队列成功！'];

            $last = date('Y-m-01 00:00:00', strtotime('-1 month'));
            $now = date('Y-m-01 00:00:00');
            $customSkuMdl = db::table('self_custom_sku')
                ->get()
                ->keyBy('id');
            $priceMdl = db::table('inventory_total_pirce')
                ->get(['warehouse_id', 'custom_sku_id', 'num', 'price']);
            $priceList = [];
            foreach ($priceMdl as $p){
                $key = $p->warehouse_id.'-'.$p->custom_sku_id;
                $p->avg_price = $p->num <= 0 ? 0.00 : bcdiv($p->price, $p->num, 2);
                $priceList[$key] = $p;
            }

            $goodsRecordMdl = db::table('cloudhouse_record as a')
                ->leftJoin('goods_transfers as b', 'a.order_no', '=', 'b.order_no')
                ->whereBetween('a.createtime', [$last, $now])
                ->get(['a.*', 'b.platform_id']);
            $list = [];
            $warehouseList = [
                1 => 'tongan_inventory',
                2 => 'quanzhou_inventory',
                3 => 'cloud_num',
                4 => 'factory_num',
                6 => 'deposit_inventory',
                21 => 'direct_inventory',
                23 => 'shenzhen_inventory',
            ];
            $platformMdl = db::table('platform')
                ->get();
            db::begintransaction();
            foreach($customSkuMdl as $c){
                foreach ($warehouseList as $k => $w){
                    foreach ($platformMdl as $p){
                        $priceFirst = $priceList[$k.'-'.$c->id]->avg_price ?? 0.00;
                        $numFirst = $c->$w ?? 0;
                        $insert = db::table('custom_sku_inventory_month')
                            ->insertGetId([
                                'warehouse_id' => $k,
                                'custom_sku_id' => $c->id,
                                'spu_id' => $c->spu_id,
                                'platform_id' => $p->Id,
                                'price_first' => $priceFirst * $numFirst,
                                'num_first' => $numFirst,
                                'year' => date('Y', strtotime($now)),
                                'month' => date('m', strtotime($now)),
                                'created_at' => date('Y-m-d H:i:s'),
                            ]);
                        if (empty($insert)){
                            throw new \Exception('库存skuId：'.$c->id.'，仓库id：'.$k.'，平台：'.$p->Id.'新增数据失败！');
                        }
                    }
                }
            }
            foreach ($goodsRecordMdl as $v){
                $key = $v->warehouse_id.'-'.$v->platform_id.'-'.$v->custom_sku_id;
                if (isset($list[$key])){
                    $list[$key]['price_type_detail_'.$v->type_detail] += $v->num * $v->price;
                    $list[$key]['num_type_detail_'.$v->type_detail] += $v->num;
                }else{
                    $priceFirst = $priceList[$v->warehouse_id.'-'.$v->custom_sku_id]->avg_price ?? 0.00;
                    $object = $warehouseList[$v->warehouse_id] ?? '';
                    $numFirst = $customSkuMdl[$v->custom_sku_id]->$object ?? 0;
                    $list[$key] = [
                        'warehouse_id' => $v->warehouse_id,
                        'platform_id' => $v->platform_id,
                        'spu_id' => $v->spu_id,
                        'custom_sku_id' => $v->custom_sku_id,
                        'price_end' => $priceFirst * $numFirst,
                        'num_end' => $numFirst,
                        'year' => date('Y', strtotime($last)),
                        'month' => date('m', strtotime($last)),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ];
                    $arr = [1,2,3,4,5,6,7,8,9,10,11,12,17,18];
                    foreach ($arr as $i){
                        $list[$key]['price_type_detail_'.$i] = 0;
                        $list[$key]['num_type_detail_'.$i] = 0;
                    }
                    $list[$key]['price_type_detail_'.$v->type_detail] = $v->num * $v->price;
                    $list[$key]['num_type_detail_'.$v->type_detail] = $v->num;
                }
            }

            foreach ($list as $v){
                $update = db::table('custom_sku_inventory_month')
                    ->where('warehouse_id', $v['warehouse_id'])
                    ->where('platform_id', $v['platform_id'])
                    ->where('spu_id', $v['spu_id'])
                    ->where('custom_sku_id', $v['custom_sku_id'])
                    ->where('year', $v['year'])
                    ->where('month', $v['month'])
                    ->update($v);
            }

            db::commit();
            return ['code' => 200, 'msg' => '更新时间：'.$last.'~'.$now.'库存sku数据成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '保存失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function confirmDeliveryTime($params)
    {
        try {
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给定出入库单标识！');
            }else{
                $goodsTransfersMdl = db::table('goods_transfers')
                    ->where('id', $params['id'])
                    ->first();
                if (empty($goodsTransfersMdl)){
                    throw new \Exception('未查询到出入库单数据！');
                }
                if (!empty($goodsTransfersMdl->delivery_time)){
                    throw new \Exception('已确认过到达时间请勿重复确认！');
                }
            }
            $save = [
                'delivery_time' => date('Y-m-d H:i:s', microtime(true)),
                'is_push'=>3
            ];
            $update =  db::table('goods_transfers')
                ->where('id', $params['id'])
                ->update($save);
            if (empty($update)){
                throw new \Exception('无数据变化！');
            }

            return ['code' => 200, 'msg' => '确认到货成功！单号为:'.$goodsTransfersMdl->order_no];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '确认到货失败！原因:'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }
}

